用C++编写输入20个整数(其中有负数),统计其中负数的个数,并计算负数的和,然后将正数从小到大进行排序(用冒泡法)并输出。

定义两个一维数组,循环输入数据,回车结束输入,正数放在一个数组中,负数放在另外一个数组中。

该回答引用chatgpt:

#include <iostream>
using namespace std;

int main() {
    const int n = 20; // 数据个数
    int nums[n]; // 存储输入的数字
    int pos[n], neg[n]; // 存储正数和负数
    int pos_count = 0, neg_count = 0; // 正数和负数的数量
    int neg_sum = 0; // 负数的总和

    // 循环输入数据
    for (int i = 0; i < n; i++) {
        cin >> nums[i];

        // 统计正数和负数的数量,并分别存储
        if (nums[i] >= 0) {
            pos[pos_count] = nums[i];
            pos_count++;
        } else {
            neg[neg_count] = nums[i];
            neg_count++;
            neg_sum += nums[i];
        }
    }

    // 冒泡排序
    for (int i = 0; i < pos_count - 1; i++) {
        for (int j = 0; j < pos_count - i - 1; j++) {
            if (pos[j] > pos[j+1]) {
                int temp = pos[j];
                pos[j] = pos[j+1];
                pos[j+1] = temp;
            }
        }
    }

    // 输出结果
    cout << "负数个数:" << neg_count << endl;
    cout << "负数总和:" << neg_sum << endl;
    cout << "正数从小到大排序结果:";
    for (int i = 0; i < pos_count; i++) {
        cout << pos[i] << " ";
    }
    cout << endl;

    return 0;
}


以上代码中,首先定义了一个 nums 数组用于存储输入的数字,然后定义了 pos 和 neg 数组分别用于存储正数和负数。接着使用一个循环读取用户输入的数字,同时统计正数和负数的数量,并将其存储到对应的数组中。同时,在存储负数时,将其加入到负数的总和 neg_sum 中。

接着使用冒泡排序算法对正数进行排序,最后输出结果。

程序的输出结果为:

-3 -5 -7 2 5 8 -9 1 -4 3 6 7 0 -2 -1 4 -8 9 -6 -10
负数个数:10
负数总和:-55
正数从小到大排序结果:0 1 2 3 4 5 6 7 8 9