程序设计,输入20个整数,统计其中非负数的个数,并计算它们的和,然后将非负数从小到大进行排序并输出的代码
时间: 2023-06-14 13:05:24 浏览: 57
下面是使用 C++ 语言实现的代码:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
const int n = 20;
int nums[n];
int pos_count = 0, pos_sum = 0;
// 输入20个整数
for (int i = 0; i < n; i++) {
cin >> nums[i];
if (nums[i] >= 0) {
pos_count++;
pos_sum += nums[i];
}
}
// 统计非负数的个数和它们的和
cout << "Count of non-negative numbers: " << pos_count << endl;
cout << "Sum of non-negative numbers: " << pos_sum << endl;
// 对非负数进行排序
sort(nums, nums + n, [](int a, int b) {
return a >= 0 && (b < 0 || a < b);
});
// 输出排序后的非负数
cout << "Sorted non-negative numbers: ";
for (int i = 0; i < pos_count; i++) {
cout << nums[i] << " ";
}
cout << endl;
return 0;
}
```
代码中使用了 `sort` 函数对非负数进行排序,排序规则是将非负数放在前面,并按从小到大的顺序排序。可以看到,使用 lambda 表达式作为排序规则可以使代码更加简洁。