#include "stdio.h"
void main()
{
int n,sum=0;
printf("请输入一个三位数:");
scanf("%d",&n);
sum=n/100+n%100/10+n%10;//百位数+十位数+个位数
printf("这个三位数各位数字之和是%d\n",sum);
}
结果:
写法很多,建议这样写,扩展性好。只要在long的范围内,不管你输入几位数(大概是19位以内吧,记不清了),求各位数字之和,代码都不要改,直接可以用。
#include
int main()
{
long num;
int sum = 0;
printf("Please input a number:");
scanf("%ld", &num);
while(num)
{
sum = sum + num%10;
num /= 10;
}
printf("answer is:%d\n", sum);
return 0;
}
#include
using namespace std;
void main()
{
int number,sum;
int a,b,c;
cout << "请输入一个三位数" <
a = number % 10;//个位
b = number / 10 % 10;//十位
c = number / 100;//百位
sum = a + b + c;
cout << "三个数之和为: " << sum <
#include
int main()
{
int Num,a,b,c;
scanf("%d",&Num);
a=Num/100;
b=(Num-100*a)/10;
c=Num%10;
printf("Sum=%d",a+b+c);
while(1);}
#include
void main()
{
int sum,a,b,c,t;
printf("Enter t:");
scanf("%d",&t);
a=t/100;
b=(t-100*a)/10;
c=t%10;
sum=a+b+c;
printf("sum=%d",sum);
}