题目描述
Write a program that reads an integer with 3 digits and adds all the digits in the integer.For example,if an integer is 932,the sum of all its digits is 9+3+2=14.
输入格式
An integer x.(100<=x<=999)
输出格式
The sum of all x's digits
样例输入
932
样例输出
14
提示
Use the % operator(求余) to extract digits, and use the / operator(取整除法) to remove the extracted digit. For instance,932 % 10 = 2 and 932 / 10 = 93.
代码:
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
cin>>a;
b = a % 10;
//cout<<b<<endl;
int temp1 = a / 10;
c = temp1 % 10;
//cout<<c<<endl;
int temp2 = temp1 / 10;
d = temp2 % 10;
//cout<<d<<endl;
cout<<b+c+d<<endl;
return 0;
}
解题关键是“%” 和 “/”两个操作,利用“/”可以将一个百位数逐一去掉最后的一位,然后再用“%”操作算出最后一位的数值。