Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

用c++编写一段程序,从键盘输入一个一维数组,将数组从大到小排列后输出,要求显示每个元素及它在原数组的下标

  1. User

    用c++编写一段程序,从键盘输入一个一维数组,将数组从大到小排列后输出,要求显示每个元素及它在原数组的下标

  2. Assistant

    以下是一份参考代码:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int main() {
        const int MAX_N = 100;
        int n;
        int a[MAX_N];
    
        // 读入数组
        cout << "请输入数组长度:";
        cin >> n;
        cout << "请输入数组元素:" << endl;
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
    
        // 排序
        sort(a, a + n, greater<int>());
    
        // 输出结果
        cout << "排序后的数组:" << endl << "下标\t元素" << endl;
        for (int i = 0; i < n; i++) {
            cout << i << "\t" << a[i] << endl;
        }
    
        return 0;
    }
    

    此程序中,我们使用 std::sort 来对数组进行排序。具体来说,我们使用了 C++11 中新引入的 greater 模板函数来指定排序顺序为从大到小。排序完成后,我们遍历数组并输出每个元素及其下标即可。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.