C++:计算一个整数的数字之和

来源:互联网 发布:c 窗口编程 编辑:程序博客网 时间:2024/05/21 11:32


算法:可以使用%提取整数中的数字,用/将提取出的数字从整数中去掉。

、比如,234%10 = 4,即可提取4,而用234/10则可以剔除4.

用一个循环,反复提取并剔除数字,直至整数中所有数字都处理完毕#include <iostream>


using namespace std;
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;
}
原创粉丝点击