算法:可以使用%提取整数中的数字,用/将提取出的数字从整数中去掉。
、比如,234%10 = 4,即可提取4,而用234/10则可以剔除4.
用一个循环,反复提取并剔除数字,直至整数中所有数字都处理完毕#include <iostream>
int sum(int );
void main()
{
cout<<"enter a number"<<endl;
int num;
cin>>num;
cout<<"sum is "<<sum(num)<<endl;
}
int sum(int a )
{
int total = 0;
int temp = 0;
while (a!=0)
{
temp = a%10;
total+=temp;//这两步可以简化为 total+=a%10;
a = a /10;
}
return total;
}