用c++按升序和降序打印数组值

printing a array values in ascending and descending order in c++

本文关键字:打印 数组 降序 c++ 升序      更新时间:2023-10-16

我在下面编写了这个程序,通过从用户那里获取I/p来打印数组,但显示了一个编译错误。我想要一个程序按升序和降序打印这些输入。

#include <iostream>
using namespace std;
int main()
{
    int a[10] = {};  // ![enter image description here][1]
    for (int i = 0; a[i] <= 9; i++)
      {
        cout << "Enter the numbers:" << endl;
        cin >> a[i];
      }
    cout << a[i] << endl;
}

错误:

![error by codeblocks][1]
||=== Build: Debug in example (compiler: GNU GCC Compiler) ===|
H:c++examplemain.cpp||In function 'int main()':|
H:c++examplemain.cpp|12|error: name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]|
H:c++examplemain.cpp|12|note: (if you use '-fpermissive' G++ will accept your code)|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

您应该在循环中打印数字,而且您的循环条件似乎是错误的。这将起作用:

#include <iostream>
using namespace std;
int main()
{
    int a[10];
    int i;
    cout << "Enter the numbers:" << endl;
    for (i = 0; i <= 9; i++)
    {
        cin >> a[i];
    }
    for (i = 0; i <= 9; i++)
    {
        cout << a[i] << endl;
    }
}

如果你想显示它们的排序,你必须首先使用sort()。