用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP