为什么不按升序打印数字
Why does this not print the numbers in ascending order
#include <iostream>
using namespace std;
int main()
{
int i,sum=0,n;
int a[10];
float avg;
cout<<"Enter how many numbers you want ";
cin>>n;
if (n>10)
n=10;
cout<<"Enter the numbers" << endl;
for (i=0;i<n;i++)
cin>>a[i];
for (i=0;i<n;i++)
{
sum=sum+a[i];
}
avg=sum/n;
cout<<"sum of array elements "<<sum << endl;
cout<<"average of array elements " <<avg << endl;
int temp;
for (int i =0; i<n; i++)
{
for (int j=1; j<n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout << "The numbers in ascending order are:" << endl;
for (int i =0; i<n; i++)
{
cout << a[i] << endl;
}
return 0;
}
当我运行这个程序时,数字以不同的顺序打印出来。
如果我使用数字 1 2 3 4 5。 他们打印为 1 5 4 3 2。
其他一切正常。 如何修复此错误?
您的排序实现不正确。由于排序的思想是在每一步找到i
最小的数字,内部循环应该从 i+1
开始,而不是从 1
开始:
for (int j=i+1; j<n; j++)
演示。
相关文章:
- 打印数字图案
- 将数字打印成文字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 我的问题是关于C++中数字和序列的重复以及如何打印它们?
- 编译器始终打印十六进制/八进制数字
- 我想使用哈希图打印非重复的数字;
- 如何在控制台上打印出带有数字 0-99 的简单数组
- 错误含义;以二进制形式打印数字
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 列中打印数字时如何避免打印垃圾?
- 如何编写一个程序来打印特定基数的前N个数字
- C++ 在地板函数之后以十六进制打印数字
- C 不将重复数字打印到输出
- 阿姆斯特朗数字打印错误
- 用数字打印所有可能的组合
- 将数字打印为字符串类型的数字
- 如何以特定格式将数字打印到字符串的中间
- 如何将矢量中的数字打印到文件中