注册 登录
编程论坛 C++教室

整数各位求和问题

duffebear 发布于 2007-11-03 13:44, 1689 次点击

题目:
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;
}

4 回复
#2
aipb2OO72007-11-03 14:36
while((ia/10)>=0)
{
sum1+=ia%10;
if((ia=ia/10)==0)
break;
}
对sum1做个是否 > 10的判断,仅取个位
#3
小小渔火2007-11-03 18:21
你的程序运行有问题:你试下 输入 19 输出是 1
#4
小小渔火2007-11-03 18:24
哦,是对的,我搞错了,还以为是19加上1等于20去了,呵。。。。。打自己一巴掌
#5
duffebear2007-11-03 21:06
回复:(小小渔火)哦,是对的,我搞错了,还以为是19...
呵呵,没事,谢谢你的测试
1