【发布时间】:2019-10-12 15:22:29
【问题描述】:
我的程序需要从命令行读取数组的大小,然后它应该用随机数填充数组。然后它应该显示数组的已排序和未排序的内容。
创建了一个 for 循环,以便将随机数读入数组并显示未排序的内容。创建了第二个 for 循环嵌套在第一个循环中,以便对数组中的内容进行排序。
#include <time.h>
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main(int argc, char * argv[], char **env)
{
int SIZE = atoi(argv[1]);
int *array = new int[SIZE];
for(int i = 0; i < SIZE; i++)
{
array[i] = rand()% 1000;
cout << i << ": " << array[i] << "\n";
for(int j = 0; j < SIZE; j++)
{
if(array[j] > array[j + 1])
{
swap(array[j], array[j +1]);
}
cout << i << ": " << array[i] << "\n";
}
}
return 0;
}
I expect an output like
0: 350
1: 264
2: 897
0:264
1:350
2:897
I'm getting an output like
0:41
0:41
0:41
0:41
1:46
1:46
1:0
1:0
2:334
2:334
2:334
2:334
【问题讨论】:
-
一个建议。将用数据填充数组的代码和对数组排序的代码分开。这不会解决您的问题,但会使调试更容易。正如发布的那样,您的程序具有未定义的行为,因为您正在访问尚未正确初始化的数组元素。