这是一个使用C ++语言计算数字总和的示例,
#include<iostream>
using namespace std;
int main() {
int x, s = 0;
cout << "Enter the number : ";
cin >> x;
while (x != 0) {
s = s + x % 10;
x = x / 10;
}
cout << "\nThe sum of the digits : "<< s;
}输出结果
Enter the number : 236214828 The sum of the digits : 36
在上面的程序中,声明了两个变量x和s,并将s初始化为零。该数字由用户输入,当数字不等于零时,它将对数字进行求和。
while (x != 0) {
s = s + x % 10;
x = x / 10;
}