整数的位数可能各不相同,给定一组整数,请按位数分类统计,输出每种位数的出现次数。c++
时间: 2023-10-06 07:09:09 浏览: 45
可以使用map来进行统计,代码如下:
```c++
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
cin >> n;
map<int, int> cnt; //使用map进行统计
for(int i = 0; i < n; i++)
{
int num;
cin >> num;
int digit = 0;
while(num > 0) //计算数字的位数
{
digit++;
num /= 10;
}
cnt[digit]++; //统计每种位数的出现次数
}
for(auto it = cnt.begin(); it != cnt.end(); it++) //遍历输出结果
{
cout << it->first << " digit: " << it->second << endl;
}
return 0;
}
```
输入示例:
```
5
1 12 345 6789 12345
```
输出示例:
```
1 digit: 1
2 digit: 1
3 digit: 1
4 digit: 1
5 digit: 1
```
相关问题
整数的位数可能各不相同,给定一组整数,请按位数分类统计,输出每种位数的出现次数。用C++
可以使用 `map` 数据结构来实现,将每个整数的位数作为键,出现次数作为值,进行统计和存储。
以下是示例代码:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
int n, num;
map<int, int> digitCount; // 用于存储每种位数的出现次数
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
int digits = 0;
while (num != 0) {
digits++;
num /= 10;
}
digitCount[digits]++;
}
for (auto it = digitCount.begin(); it != digitCount.end(); it++) {
cout << it->first << "位数:" << it->second << "个" << endl;
}
return 0;
}
```
输入格式为:
```
整数个数
整数1 整数2 ... 整数n
```
输出格式为:
```
x位数:y个
```
其中 x 为位数,y 为该位数出现的次数。
现有n个整数,将其中个位数为k的数进行累加求和。c++完整代码
以下是一个简单的C++代码示例,用于计算给定整数数组中个位数为k的数的总和:
```cpp
#include <iostream>
int main() {
int n, k;
std::cin >> n >> k;
int sum = 0;
for (int i = 0; i < n; i++) {
int x;
std::cin >> x;
if (x % 10 == k) {
sum += x;
}
}
std::cout << sum << std::endl;
return 0;
}
```
该程序首先从标准输入中读取整数n和数字k,然后在循环中读取n个整数,并将它们的个位数与k进行比较。如果它们的个位数等于k,则将它们的值加到sum中。最后,程序输出sum的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)