[英]C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them
[英]C program to print sum of squares of digits of a given number?
我想编写一个ac程序,打印给定数字的平方和。 例如,如果给定数字为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
您的程序将添加3 2 +2 2 +1 2并停止,因为下一位数字恰好为零。 永远不会添加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的倍数时循环结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.