for(int i = N; i > 0 ; i = i/10)
{
int r = N % 10; // calculating remainder of UNMODIFIED input, so will
// ALWAYS be last digit
int sum = 0; // you are initializing the sum to 0 for every single iteration
sum = sum + r; // so this will *always* result in 0 + N % 10
printf("The sum is : %d", sum);
}
要解决此问题,您只需初始化总和一次以收集所有个位数。此外,您需要使用修改后的值:
int sum = 0;
for(int i = N; i > 0 ; i = i/10)
{
int r = i % 10;
// ^ (!)
sum += r; // alternative variant...
printf("The sum is : %d\n", sum);
// ^^ for better output formatting
}
直到现在,我们仍然在每次迭代中打印总和。如果您想了解总和的演变方式(假设输入为 1210),这可能很有用:
The sum is 0
The sum is 1
The sum is 3
The sum is 4
但实际上,您宁愿只打印结果,不是吗?因此,您也可以将打印移出循环:
for(...)
{
...
}
printf("The sum is : %d\n", sum);
替代变体:如果您以后不再需要 N 的值,您可以直接对其进行迭代:
for( ; N > 0; N /= 10)
// ^ empty initialization, nothing to be done...
{
int r = N % 10; // NOW using N is fine...
...
}
最后:如果您比较 with!=
而不是>
,您也可以涵盖负输入(因为您使用有符号整数......)。
根据问题编辑:
它像这样询问输入和输出。输入 3 12345 31203 2123 输出 15 9 8
好吧,在这种情况下,您需要一个双循环:
int t;
// well, actually, you should check if you did get correct input:
if(scanf("%d", &t) != 1))
{
// invalid input
// appropriate error handling, e. g. printing a message and:
return -1;
}
for( ; t > 0; --t) // handles the number of tasks to solve
{
int n; // inside loop: read in a new value with every task
scanf("%d", &n); // TODO: check input, see above
int sum = 0;
for(...) { ... } // loop handling the input value, see above
printf(...);
}