因此,我编写了对数字进行排序的程序,但每当我执行它时,它都会将最小的随机数添加为“已排序数字”行中的第一个。
代码如下:
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>
using namespace std;
int main(){
const int MAX_SIZE = 100;
int numbers[MAX_SIZE];
int numElements;
cout << "=============================" << endl;
cout << "Welcome to BubbleSort Program" << endl;
cout << "=============================" << endl;
cout << endl;
cout << "How many random numbers do you want us to produce? ";
cin >> numElements;
cout << endl;
srand(static_cast<unsigned int>(time(0)));
cout << "=============================" << endl;
cout << "Random numbers: " << endl;
cout << "=============================" << endl;
for(int i = 0; i < numElements; i++){
numbers[i] = (rand()%100) + 1;
cout << numbers[i] << endl;
if(i == numElements){
cout << "i";
}
}
int exchanges;
int temp;
int j;
cout << "=============================" << endl;
cout << "Sorted numbers: " << endl;
cout << "=============================" << endl;
for(int i = 0; i <= numElements; i++){
for(int j = 0; j < numElements; j++){
if(numbers[j] > numbers[j + 1]){
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
for(int i = 0; i <= numElements; i++) {
cout << numbers[i] << endl;
}
cout << "=============================" << endl;
return 0;
}
输出示例:
============================= Welcome to BubbleSort Program =============================
How many random numbers do you want us to produce? 3 ============================= Random numbers: ============================= 69 8 5 ============================= Sorted numbers: ============================= -858993460 5 8 69 ============================= Press any key to continue . . .
WTF 是-858993460?!
最佳答案
您正在访问未初始化的内存 -
for(int i = 0; i <= numElements; i++) { // <-- no, stop at < -- see above.
for(int j = 0; j < numElements; j++) // <-- you use j+1 below
应该是
for (int i = 0; i < numElements; i++) { // <-- also not initialized.
for (int j = 0; j < numElements - 1; j++) // <-- like so.
关于c++ - 用 C++ 对数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20509564/