for 循环和模运算符

for loops and modulo operator

Write a program that calculates the sum of the digits of an integer. For example, the sum of the digits of the number 2155 is 2 + 1 + 5 + 5 or 13. The program should accept any arbitrary integer typed in by user.

我可以使用 while 循环让它工作,但如果我将它与 for 循环相结合,程序会计算除最后一个数字之外的所有数字。为什么是这样?

#include <stdio.h>

int main(void)
{
    int i, num, sum = 0, temp;

    printf("Enter the number:\n");
    scanf("%i", &num);

    printf("Test for num: %i\n", num); //both num & temp return same number
    temp = num;
    printf("Test for temp: %i\n", temp);

    //while (num > 0)
    for (i = 0; i <= temp; i++)  //replacing temp w/ num will skip last num
    {
        sum += num % 10;
        //sum += right;
        num /= 10;
    }

    printf("Given number = %i\n", temp);
    printf("Sum of digits of %i = %i", temp, sum);

    return (0);
}

正如您注释掉的那样,for 循环中有 num,您计算的是 i 与原始数字的被除数,而不是 while num > 0

如果你有,例如,num = 158,循环将执行,然后将 num 设置为 15。i 递增到 1。因此 i < num,因此它再次执行。这次循环后,num == 1,i == 2,所以不会执行,158的1不加。

如果您的最高位数大于或等于位数,则您在 for 循环中使用 num 的代码将起作用。否则,它不会。

您可以去掉 i 并在 for 循环中简单地使用 num。

for(;num > 0; num /= 10)
    sum += num%10;

注:

for (i = 0; i <= temp; i++)

这是不公平的——如果 temp 例如 543你肯定不会执行这个循环 544 次(尽管结果可以,因为在其多数迭代中的循环只会将 0 添加到已经正确的结果中。

您的程序及其原始 while 循环

while (num > 0)
{
    sum += num % 10;
    num /= 10;
}

适用于 相对较小的数字,我。 e.在int范围内*),我测试过,例如

Enter the number:
1234
Test for num: 1234
Test for temp: 1234
Given number = 1234
Sum of digits of 1234 = 10

Enter the number:
123456789
Test for num: 123456789
Test for temp: 123456789
Given number = 123456789
Sum of digits of 123456789 = 45

但是,例如

Enter the number:
10000000001
Test for num: 1410065409
Test for temp: 1410065409
Given number = 1410065409
Sum of digits of 1410065409 = 30

您可能会看到 scanf() 函数将 "big" 数字 10000000001 读取为 1410065409

但是你的while循环的逻辑没有问题,数字1410065409的结果是正确的。


(*) - int 最常见的 int 实现范围(作为 32 位数字)是

              from  -2.147.483.648  to  +2.147.483.647.

执行此操作,在 for 循环中打印出变量 i 并查看它 运行 的频率。这是低效的并且明显浪费资源。

您还应该考虑以下几点 ?

时间复杂度是多少? while 循环与使用 temp 的 for 循环有何不同?

当你改成for循环时,你没有考虑while循环中的变量num发生了什么。考虑一下,一个 n 位数的数字介于 10^(n-1)10^n 之间。如果设n为N中的位数,则不等式为10^(n-1) <= N < 10^n。由此我们发现时间复杂度为O(log(n))。 num.

中大概有log10(num)个数字

您的解决方案是正确的,因为它产生了正确的答案,但性能低下。首先,您应该减少 for 循环索引。

 for (i = temp ; i !=0; i /= 10)

使用 for 循环会更正确。这将 运行 与 while 循环相同的次数,但需要递减 i 并检查迭代是否 i != 0