编写一个程序来计算整数的位数之和。例如,数字2155的数字之和为2 + 1 + 5 + 5或13.程序应接受用户输入的任意整数。
我可以使用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与原始数字的红利,而不是num > 0
。
例如,如果你有num = 158,则循环将执行,然后将num设置为15. i增加到1.因此i <num,所以它再次执行。这次循环之后,num == 1和i == 2.因此它不会执行,并且不会添加158中的1。
如果您的最高位数大于或等于位数,则for循环中带有num的代码将起作用。否则,它不会。
你可以摆脱我,只需在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;
}
适用于相对较小的数字,i。即例如,在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()
函数读取“大”数字10000000001
为1410065409
!
但这不是while
循环逻辑的问题,数字1410065409
的结果是正确的。
(*) - int
范围最常见的int
实现(32位数字)是
from -2.147.483.648 to +2.147.483.647.
这样做,在你的for循环中打印变量qazxsw poi,看看它运行的频率。这是低效的,并且明显浪费资源。
你还应该考虑以下几点?
什么是时间复杂度?有关while循环与使用temp的for循环有什么不同?
当您更改为for循环时,您没有考虑while循环中变量num发生了什么。考虑一下,n个数字的数字介于i
包含和10^(n-1)
之间。如果我们让10^n
为N中的位数,则不等式为n
。由此我们发现时间复杂度为O(log(n))。 num中有大约10^(n-1) <= N < 10^n
数字。
您的解决方案是正确的,因为它产生了正确的答案但效率低下。首先,你应该减少for循环索引。
log10(num)
使用for循环会更正确。这将与while循环运行相同的次数,但需要递减i并检查 for (i = temp ; i !=0; i /= 10)
是否迭代。