| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1685 人关注过本帖
标题:整数各位求和问题
只看楼主 加入收藏
duffebear
Rank: 1
等 级:新手上路
威 望:2
帖 子:172
专家分:0
注 册:2007-1-30
收藏
 问题点数:0 回复次数:4 
整数各位求和问题

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

搜索更多相关主题的帖子: 整数 sum number 求和 print 
2007-11-03 13:44
aipb2OO7
Rank: 1
等 级:新手上路
帖 子:41
专家分:0
注 册:2007-8-30
收藏
得分:0 
while((ia/10)>=0)
{
sum1+=ia%10;
if((ia=ia/10)==0)
break;
}
对sum1做个是否 > 10的判断,仅取个位

[glow=255,yellow,5]菜鸟一个.以后靠你们了..[/glow]
2007-11-03 14:36
小小渔火
Rank: 1
等 级:新手上路
帖 子:28
专家分:0
注 册:2007-5-5
收藏
得分:0 
你的程序运行有问题:你试下 输入 19 输出是 1
2007-11-03 18:21
小小渔火
Rank: 1
等 级:新手上路
帖 子:28
专家分:0
注 册:2007-5-5
收藏
得分:0 
哦,是对的,我搞错了,还以为是19加上1等于20去了,呵。。。。。打自己一巴掌
2007-11-03 18:24
duffebear
Rank: 1
等 级:新手上路
威 望:2
帖 子:172
专家分:0
注 册:2007-1-30
收藏
得分:0 
回复:(小小渔火)哦,是对的,我搞错了,还以为是19...
呵呵,没事,谢谢你的测试

死后定当长眠 生前何须久睡
2007-11-03 21:06
快速回复:整数各位求和问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011297 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved