题目要求编写一个程序,输入20个整数,统计并输出它们中非负数的个数,并计算输出它们的和。然后按照从小到大的顺序进行排列并输出,每行输出一个数据。
时间: 2024-05-05 15:18:10 浏览: 96
没问题,我可以回答你的问题。下面是代码实现:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
const int kInputCount = 20;
std::vector<int> nums(kInputCount);
for (int i = 0; i < kInputCount; ++i) {
std::cin >> nums[i];
}
int nonNegativeCount = 0;
int sumOfNonNegatives = 0;
std::vector<int> nonNegatives;
for (int num : nums) {
if (num >= 0) {
nonNegativeCount += 1;
sumOfNonNegatives += num;
nonNegatives.push_back(num);
}
}
std::sort(nonNegatives.begin(), nonNegatives.end());
std::cout << "非负数的个数为: " << nonNegativeCount << std::endl;
std::cout << "非负数的和为: " << sumOfNonNegatives << std::endl;
std::cout << "从小到大排序后的非负数为:" << std::endl;
for (int num : nonNegatives) {
std::cout << num << std::endl;
}
return 0;
}
```
输入20个整数,程序会统计非负数的个数和它们的和,并将它们从小到大排序并输出。例如输入:``1 3 -5 -7 0 12 3 15 -6 -9 10 -1 6 8 30 20 -15 -10 0 5``,输出:
```
非负数的个数为: 9
非负数的和为: 86
从小到大排序后的非负数为:
0
0
1
3
3
5
6
8
10
12
15
20
30
```
阅读全文