易百教程

除法和模运算符

假设有一个包含45个程序错误(bug)和一个由七个开发人员组成的程序。将在开发人员之间平均分配错误,并确定每个开发人员的数量。

想要弄清楚剩下多少程序错误(bug)。

参考以下代码

#include <stdio.h>

int main(void)
{
  int bugs = 45;                   // Number of bugs in the code
  int developers = 7;              // Number of developers
  int bugs_per_developer = 0;      // Number of bugs per developer
  int bugs_left_over = 0;          // Number of bugs left over

  // Calculate how many bugs each developer gets when they are divided up
  bugs_per_developer = bugs/developers;     // Number of bugs per developer
  printf("You have %d developers and %d bugs\n", developers, bugs);
  printf("Give each developer %d bugs.\n", bugs_per_developer);

  // Calculate how many bugs are left over
  bugs_left_over = bugs%developers;//
  printf("There are %d bugs left over.\n", bugs_left_over);
  return 0;
}

执行上面示例代码,得到以下结果:

hema@ubuntu:~/book$ gcc -o main main.c
hema@ubuntu:~/book$ ./main
You have 7 developers and 45 bugs
Give each developer 6 bugs.
There are 3 bugs left over.

程序步骤

使用以下语句声明和初始化四个整数变量:bugs, developers, bugs_per_developerbugs_left_over

int bugs = 45;               // Number of bugs in the jar
int developers = 7;          // Number of developers
int bugs_per_developer = 0;  // Number of bugs per developer
int bugs_left_over = 0;      // Number of bugs left over

通过使用除法运算符/将错误数量(bugs)除以开发人员数量(developers)得到每个开发人员的错误数量:

bugs_per_developer = bugs/developers;     // Number of bugs per developer

接下来的两个语句输出结果值,包括存储在bugs_per_developer中的值:

printf("You have %d developers and %d bugs\n", developers, bugs);
printf("Give each developer %d bugs.\n", bugs_per_developer);

当操作数是整数时,除法运算符总是产生整数结果。将45除以7的结果是6,余数为3
可以使用模数运算符(%)计算得到余数:

bugs_left_over = bugs%developers;

最后,在最后一个语句中输出余数:

printf("There are %d bugs left over.\n", bugs_left_over);