用c++写出代码实现计算在区间 1到 n的所有整数中,数字x(0≤x≤9) 共出现了多少次?例如,在 1到11中,即在 1,2,3,4,5,6,7,8,9,10,11 中,数字 1 出现了 4 次
时间: 2023-10-09 10:08:19 浏览: 47
您好!以下是使用 C++ 编写的代码,用于计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)出现的次数:
```cpp
#include <iostream>
int countOccurrences(int n, int x) {
int count = 0;
for (int i = 1; i <= n; i++) {
int num = i;
while (num > 0) {
if (num % 10 == x) {
count++;
}
num /= 10;
}
}
return count;
}
int main() {
int n, x;
std::cout << "请输入整数 n:";
std::cin >> n;
std::cout << "请输入数字 x:";
std::cin >> x;
int occurrences = countOccurrences(n, x);
std::cout << "数字 " << x << " 在区间 1 到 " << n << " 中出现了 " << occurrences << " 次。" << std::endl;
return 0;
}
```
您可以运行这段代码,并输入相应的整数 n 和数字 x,即可得到数字 x 在区间 1 到 n 中出现的次数。希望对您有帮助!如果您有任何疑问,请随时提问。