C语言 C程序打印给定数字的数字平方和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28457757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C program to print sum of squares of digits of a given number?
提问by ThisSiteSucks
I want to write a c program that prints the sum of the squares of a given number. For example, if the given number is 456, the output would be 4^2+5^2+6^2=16+25+36=77.
我想编写一个 ac 程序来打印给定数字的平方和。例如,如果给定的数字是 456,则输出将是 4^2+5^2+6^2=16+25+36=77。
So i have written this code and i want to know why it doesn't work if the user gives a number like 100,101,102 or 200,300 etc. It works fine for other numbers. I guess it has something to do with the dowhile loop. Please help me.
所以我写了这段代码,我想知道为什么如果用户给出一个像 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();
}
回答by dasblinkenlight
Your stopping condition is wrong: q%10!=0will become "true" as soon as you reach the first zero in a decimal representation. For example, for a number 6540321your program would add 32+22+12, and stop, because the next digit happens to be zero. Squares of 6, 5, and 4 would never be added.
您的停止条件是错误的:q%10!=0只要您达到十进制表示中的第一个零,就会变为“真”。例如,对于一个数字,6540321您的程序将添加 3 2+2 2+1 2,然后停止,因为下一位数字恰好为零。永远不会添加 6、5 和 4 的平方。
Use q != 0condition instead to fix this problem. In addition, consider replacing
改用q != 0条件来解决这个问题。另外,考虑更换
t=t+pow(r,2);
with a more concise and C-like
用更简洁和类似C的
t += r*r;
回答by Spikatrix
Change
改变
while(q%10!=0);
To
到
while(q);
Which is the short for
哪个是缩写
while(q!=0);
This is done to prevent to loop from ending once the value of qis a multiple of 10.
这样做是为了防止循环在值q是 10 的倍数时结束。

![C语言 警告:在将函数地址分配给函数指针时从不兼容的指针类型分配 [默认启用]](/res/img/loading.gif)