[英]program to find the sum of digits
我无法找出问题所在:
#include<stdio.h>
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<space>
,但不匹配12
。 将"%d "
替换为"%d "
"%d"
。
您不要以“ \\ n”终止printf()
。 通常,输出流(stdout)是行缓冲的。 这意味着除非使用fflush()
强制打印不完整的行,否则无需打印。 但是没有必要。
只需在您的printf()
添加一个“ \\ n”
printf("hence the simplified result is %d\n", count);
一个问题是您在每个循环中而不是在循环之后打印计数。
这不是问题,但是C具有算术赋值(又称复合赋值 )运算符,可以更容易理解。 例如, a /= 10
等效于a = a/10
。
我认为printf语句应该在循环之外。
将printf移出循环。 这将解决它。
请尝试以下操作:
#include<stdio.h>
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.