C程序打印给定数字的数字平方和?

C program to print sum of squares of digits of a given number?

我想编写一个 c 程序来打印给定数字的平方和。 例如,如果给定的数字是 456,则输出将是 4^2+5^2+6^2=16+25+36=77.

所以我写了这段代码,我想知道为什么如果用户给出 100,101,102 或 200,300 等数字它就不起作用。它对其他数字也能正常工作。我想这与 dowhile 循环有关。请帮助我。

#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
 int n,t=0,r,q;
 printf("Enter the number to be tested: ");
 scanf("%d",&n);
 q=n;
 do
 {
      r=q%10;
      t=t+pow(r,2);
      q=q/10;
 }
 while(q%10!=0);
 printf("%d",t);
 getch();


}

您的停止条件是错误的:q%10!=0 将在您到达十进制表示形式的第一个零后立即变为 "true"。例如,对于数字 6540321,您的程序将添加 32+22+12,然后停止,因为下一位恰好是零。永远不会添加 6、5 和 4 的平方。

使用 q != 0 条件来解决这个问题。另外,考虑更换

t=t+pow(r,2);

更简洁,更像 C

t += r*r;

改变

while(q%10!=0);

while(q);

的缩写
while(q!=0);

这样做是为了防止一旦 q 的值是 10 的倍数就结束循环。