题目:
3. (8 marks) (Nested loops) Write a program to find the sum of digits of a given integer
such that the final sum that gets printed is a one digit number. So if your number is 34,
the sum is 7, so we print the result as 7. If the number is 3524, sum is 14. Since 14 is
a 2-digit number , we have to again find the sum of 14 which is 5, so we print 5 as the output.
我翻译一下: 求一个整数的各位的和,如果这个和只有 1 位,就输出;如果这个和位数超过 1 位,
就求这个和的各位的和,直到最后结果为 1 位为止,下面给了几个例子
Sample Input / Output (3 different samples are given for your convenience ,
you may show only 1 in your script file).
Enter an integer : 132
Output :
Sum=6
Enter an integer : 2456
Output :
Sum=8
Enter an integer : 99999
Output :
Sum=9
这是我写的,devcpp测试通过,但感觉自己写的效率比较低下,大虾有好方法的回个帖,谢谢
#include<iostream>
using namespace std;
int bitsum(int);
int main()
{
int sum;
cout<<"Enter an integer :";
cin>>sum;
while(sum>=10)
{
sum=bitsum(sum);
}
cout<<"output:"<<endl;
cout<<sum;
cout<<endl;
system("pause");
return 0;
}
int bitsum(int ia)
{
int sum1=0;
while((ia/10)>=0)
{
sum1+=ia%10;
if((ia=ia/10)==0)
break;
}
return sum1;
}