用 C++ 統計包含數字 4 的從 1 到 n 的數字


在本教程中,我們將介紹一個程式,以找到從 1 到 n 且包含數字 4 的數字。

為此,我們將獲得一個數字 n。我們的任務是計算所有包含 4 作為其一個數字的數字,並將結果打印出來。

示例

 線上演示

#include<iostream>
using namespace std;
bool has4(int x);
//returning sum of digits in the given numbers
int get_4(int n){
   int result = 0;
   //calculating the sum of each digit
   for (int x=1; x<=n; x++)
      result += has4(x)? 1 : 0;
   return result;
}
//checking if 4 is present as a digit
bool has4(int x) {
   while (x != 0) {
      if (x%10 == 4)
         return true;
      x = x /10;
   }
   return false;
}
int main(){
   int n = 328;
   cout << "Count of numbers from 1 to " << n
      << " that have 4 as a digit is "
      << get_4(n) << endl;
   return 0;
}

輸出

Count of numbers from 1 to 328 that have 4 as a digit is 60

更新日期:2020 年 2 月 5 日

355 人閱讀

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.