一题“C++ 题目” 给分拉。。~~~~

来源:百度知道 编辑:UC知道 时间:2024/05/29 05:32:15
编写程序,从键盘读入整数,计算出各位数字之和,直到为一位数字。例如输入数据是 8759。
sum=8+7+5+9=29
sum=2+9=11
sum=1+1=2
可以使用下面具有一个整形数据成员和成员函数的类结构来接收用户输入的数据,进行和计算,然后显示结果。
class Number
{
private:
int num;
public:
void getdate();
int adddigits();
void display();
};
结果显示为下面的格式:
The sum of digits of 8759 is 2.

#include<iostream>
using namespace std;

class Number
{
private:
int num;
public:
void getdate()
{
cin>>num;
}
int adddigits()
{
int sum=num;
while(sum>9)
{
int temp=0;
while(sum>0)
{
temp+=sum%10;
sum/=10;

}
sum=temp;
}
return sum;
}
void display()
{
cout<<"The sum of digits of "<<num<<" is "<<adddigits()<<'.'<<endl;
}
};

int main(void)
{
Number N;
N.getdate();
N.adddigits();
N.display();

return 0;
}

//Too easy!