简体   繁体   English

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.例如,数字 2155 的数字之和为 2 + 1 + 5 + 5 或 13。程序应接受用户输入的任意整数。

I can get it working using while loop but if I sub it w/ a for loop, the program calculates all of numbers except the last.我可以使用 while 循环让它工作,但如果我用for循环将其子化,程序将计算除最后一个之外的所有数字。 Why is this?为什么是这样?

#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);
}

With num in the for loop as you have commented out, you are counting i against the dividend of the original number, not while num > 0 .正如您所评论的那样,在 for 循环中使用 num ,您将 i 与原始数字的被除数相加,而不是num > 0

If you have, for example, num = 158, the loop would execute, then set num to 15. i is incremented to 1. Thus i < num, so it executes again.例如,如果您有 num = 158,循环将执行,然后将 num 设置为 15。i 增加到 1。因此 i < num,因此它再次执行。 After the loop this time, num == 1 and i == 2. Hence it will not execute and the 1 of 158 is not added.这次循环之后,num == 1 和 i == 2。因此它不会执行并且不会添加 158 中的 1。

If your highest digit is greater than or equal to the number of digits, your code with num in the for loop would work.如果您的最高位数大于或等于位数,则 for 循环中带有 num 的代码将起作用。 Otherwise, it will not.否则,它不会。

You can get rid of i and simply use num in your for loop.您可以摆脱 i 并在 for 循环中简单地使用 num 。

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

Note:笔记:

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

It is not fair - if temp is for example 543 , you certainly don't perform this loop 544 times (in spite the result is OK as the loop in its majority iterations only adds 0 to already correct result).这是不公平的 - 如果temp是例如543你当然不会执行这个循环 544 次(尽管结果是可以的,因为它的多数迭代中的循环只将0添加到已经正确的结果)。

Your program with its original while loop您的程序及其原始while循环

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

works OK for relatively small numbers , ie in the int range *) , I tested it, for example对于相对较小的数字,即在int范围*) 中,工作正常,例如,我对其进行了测试

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

or或者

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

But, for example但是,例如

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

You may see that the scanf() function read the "big" number 10000000001 as 1410065409 !您可能会看到scanf()函数将“大”数字10000000001读取为1410065409

But it is not a problem with the logic of your while loop, the result for the number 1410065409 is correct.但这不是while循环的逻辑问题,数字1410065409的结果是正确的。


(*) - int range for the most common implementations of int (as 32 bits numbers) is (*) - int最常见实现的int (作为 32 位数字)是

              from  -2.147.483.648  to  +2.147.483.647.

Do this, print out the variable i in side your for loop and see how often it runs.这样做,打印出 for 循环中的变量i并查看它运行的频率。 This is inefficient and a clear waste of resources.这是低效的,而且是明显的资源浪费。

You should also be considering the following ?您还应该考虑以下问题吗?

What is the time complexity?什么是时间复杂度? What is different about that of the while loop vs your for loop using temp? while 循环与使用 temp 的 for 循环有何不同?

When you changed to a for loop you did not consider what was happening the variable num in the while loop.当您更改为 for 循环时,您没有考虑 while 循环中变量 num 发生了什么。 Consider, a number with n digits is between 10^(n-1) inclusive and 10^n exclusive.考虑一下,具有 n 位数字的数字介于10^(n-1)10^n If we let n be the number of digits of in N, then the inequality is 10^(n-1) <= N < 10^n .如果我们让n是 N 中的位数,那么不等式是10^(n-1) <= N < 10^n From this we find that the time complexity is O(log(n)).由此我们发现时间复杂度是 O(log(n))。 There are roughly log10(num) digits in num. log10(num)中大约有log10(num)数字。

Your solution is correct in that is produces the correct answer but is ineffecient in performance.您的解决方案是正确的,因为它产生了正确的答案,但性能低下。 Firstly, you should be reducing the for loop index as such.首先,您应该减少 for 循环索引。

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

This would be more correct using a for loop.使用 for 循环会更正确。 This would run the same number of times as the while loop, but would need to decrement i and check if i != 0 for iteration.这将运行与 while 循环相同的次数,但需要递减 i 并检查i != 0是否进行迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM