程序找到数字的总和
我无法弄清楚这个问题:
#include int main() { int a,b,count ; count =0; printf("enter the value for a "); scanf("%d ",&a); while(a>0) { b=a%10; count=b+count; a=a/10; printf ("hence the simplified result is %d",count); } return 0; }
你的代码中有一个无声的杀手 :
scanf("%d ",&a);
scanf中的额外空间将使输入数字变得更难:这将匹配12
,但不匹配12
。 将"%d "
替换为"%d "
"%d"
。
您没有使用“\ n”终止printf()
。 输出流(stdout)通常是行缓冲的。 这意味着除非用fflush()
强制它们,否则不需要打印不完整的行。 但是没有必要这样做。
只需在printf()
添加“\ n” printf()
printf("hence the simplified result is %d\n", count);
一个问题是你用每个循环打印计数,而不是在循环之后。
不是问题,但C具有更易读的算术赋值(也称为复合赋值 )运算符。 例如, a /= 10
相当于a = a/10
。
我认为printf语句应该在循环之外。
将printf移出循环。 这将解决它。
请尝试以下方法:
#include int main() { int a,b,count ; count =0; printf("enter the value for a "); scanf("%d",&a); while(a>0) { b=a%10; count=b+count; a=a/10; } printf ("hence the simplified result is %d",count); return 0; }