C++ 程式求給定數字的數字之和
以下是使用 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; }
廣告