编写函数,计算一个整数各位数字之和

 时间:2024-10-13 02:27:27

语言编程如下:

#include <iostream>

using namespace std;

void sum(int n){

int m;//暂存各位数

int res=0;//结果

cout<<"res=";

while(n){

m=n%10;//当前个位数

n=n/10;//除个数位之外的数

//输出样式

if(n==0)

cout<<m;

else

cout<<m<<"+";

res+=m;//求和

}

cout<<"="<<res<<endl;

}

int main() {

int n;

cout<<"n:";

cin>>n;

cout<<"n的各位数之和";

sum(n);

return 0;

}

编写函数,计算一个整数各位数字之和

扩展资料:

整数各位数字之和函数编程思路

给定一个正整数,求它的各位数字之和。

例如,给出整数1236,那么计算

1+2+3+6=12

得到结果为:12。

1、求和函数sum

编写一个函数完成求和的功能:

原型:int sum();

功能:返回整数num的各个位数字之和。

2、Input

一个int类型的整数N。

3、Output

输出N的各位数字之和。

Sample Input

1236

Sample Output

12

  • python素数判断代码
  • python字符串逆序输出
  • python大小写字母转换
  • python 的列表如何进行升序排序?
  • python编程摄氏度转换华氏度
  • 热门搜索
    血透是什么 喝什么养胃 bug什么意思 有什么好玩的手游 军团长是什么级别 三顾茅庐是什么意思 polo衫配什么裤子 gre是什么 快乐是什么作文 语不惊人死不休什么意思