我正在学习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);
Run Code Online (Sandbox Code Playgroud)
我的问题是:
任何人都可以帮我理解这个程序的流程吗?为什么要使用Modulo?为什么有= n/10
我做过的经历:
当我删除d = n%10; 输出行打印出数字seperatley.因此它不算.
即123 = 6 - >它给了我136
当我删除行n = n/10时它没有显示输出.printf语句有一个参数's'
提前致谢!
以在模数d = n % 10使得d等于的最后一位n在底座10 n = n / 10去除的最后一位数字n.
模数基本上是剩余的,所以我们说n = 123.然后n / 10是12和n % 10是3.
删除每次循环运行之间不会改变的n = n / 10平均值n,因此循环条件n > 0始终为true,因此循环一直持续到手动终止程序为止.
这是一个程序的跟踪n = 123.最初d并且s都是零.
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2527 次 |
| 最近记录: |