循环和模数

时间:2011-04-26 22:54:21

标签: c

我正在学习C并且我很难理解循环和模数的使用。我知道循环用于缩短程序,Modulo用于排除剩余部分。我的任务是“编写一个C程序来查找单个正整数的总和”。

我花了几个小时试图理解这个问题。我也做过实验。

    int  n,d=0,s=0;
    printf("\nEnter a number\n\n");
    scanf("%d",&n);

while(n>0) { d = n%10; s = s+d; n = n/10; } printf("\n sum of the individual digits = %d",s);

我的问题是:

有谁能帮我理解这个程序的流程?为什么要使用Modulo?为什么有n = n / 10

我做过的实验:

当我删除d = n%10;输出行打印出数字seperatley。因此它不算。

即123 = 6 - >它给了我136

当我删除行n = n / 10时它没有显示输出。 printf语句有一个参数's'

提前致谢!

3 个答案:

答案 0 :(得分:6)

使用d = n % 10中的模数使d等于基数10中n的最后一位数。n = n / 10删除n中的最后一位数字。

Modulo基本上是剩下的,所以让我们说n = 123。然后n / 1012n % 103

删除n = n / 10意味着n在每次循环运行之间不会发生变化,因此循环条件n > 0始终为真,因此循环一直持续到手动终止该程序。

以下是n = 123的程序跟踪。最初ds均为零。

 while (n > 0) {  // n is 123, which is greater than zero, so we enter the loop
     d = n % 10;  // 123 % 10 is 3, so d is now 3
     s = s + d;   // 0 + 3 is 3, so s is now 3
     n = n / 10;  // 123 / 10 is 12, so n is now 12.
 }                // go back to the top of the loop
 while (n > 0) {  // n is 12, which is still greater than zero
     d = n % 10;  // 12 % 10 is 2, so d is now 2
     s = s + d    // 3 + 2 is 5, so s is now 5
     n = n / 10;  // 12 / 10 is 1, so n is now 1
 }                // go back to the top again
 while (n > 0) {  // n is 1, which is still greater than zero
     d = n % 10;  // 1 % 10 is 1, so d is now 1
     s = s + d;   // 5 + 1 is 6, so s is now 6
     n = n / 10;  // 1 / 10 is 0, so n is now 0
 }                // go back to the top
 while (n > 0) {  // n is 0, which is not greater than zero, so we skip
                  // to after the loop body
 printf("\n sum of the individual digits = %d",s);

答案 1 :(得分:2)

想象一下,你有一张纸上有一个洞,它的大小足以显示一位数。要获得数字的总和,您必须将该纸张放在您的数字上,以便显示数字。你把那个数字写在某个地方。然后将数字向右滑动,使十位数位于孔下方。您将其添加到您记下的前一个数字,依此类推,直到没有剩余数字为止。

带孔的纸是模数操作,每步向右滑动数字除以10操作。

并举一个具体的计算例子:

说数字是576。

576 % 10 = 6

所以我们选择了6,我们将其添加到0的运行总和得到6.然后你按10整数除法:

576 / 10 = 57

现在你模数:

57 % 10 = 7

所以我们选择了7并且可以将其添加到6的运行总和中得到13.然后它再次整数除以10:

57 / 10 = 5

再次模数:

5 % 10 = 5

我们摘下了最后一位数字并将其添加到运行总和中以获得18 - 数字的总和。然后我们再次除以10:

5 / 10 = 0

由于那是零,循环条件(n > 0)现在是假的,我们结束了。

因此,使用模数来挑选当前数字的最右边数字,并使用除法将每个数字依次作为最右边的数字。

答案 2 :(得分:0)

试试这些:

int n = 12;
printf("%d\n", n / 10);

int j = 12;
printf("%d\n", j % 10);

int x = 13;
x = x / 10;   // right hand side of "=" get evaluated first
printf("%d\n", x);

在每种情况下观察输出。

关于你的最后一点:

while (n > 0)
{
    // some code.
}

这意味着:n的值大于零运行some code。现在,如果你不改变nsome code将会永远运行。 HTH。