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;
}

更新於: 6 月 26 日,2020 年

11K+ 瀏覽量

展望你的 職業

獲得結課證書

開始吧
廣告