【发布时间】:2020-10-12 15:14:02
【问题描述】:
该程序旨在根据用户输入的数组大小给出随机数。 rand() 正在工作并根据用户提供输出元素。
问题在于,当涉及到排序的部分时,数组的元素似乎从不同的值发生变化。
#include <iostream>
#include <ctime>
using namespace std;
int SizeArray = 0;
int setArray[] = { NULL };
int tempA, half;
int main() {
cout << "Enter number of elements: ";
cin >> SizeArray;
srand(time(0));
for (int i = 0; i < SizeArray; i++) {
setArray[i] = 51 + rand() % (100 - 51);
}
cout << "\n\n\nraw input " << endl;
for (int i = 0; i < SizeArray; i++) {
cout << setArray[i] << "\t";
}
half = SizeArray / 2;
cout << "\n\n\nfirst half " << endl;
for (int j = 0; j < half; j++){
for (int i = 0; i < half; i++){
if (setArray[i] > setArray[i + 1]){
tempA = setArray[i];
setArray[i] = setArray[i + 1];
setArray[i + 1] = tempA;
}
}
}
for (int i = 0; i < half; i++){ //to print the sorted array
cout << setArray[i] << "\t";
}
cout << "\n\n\nsecond half " << endl;
for (int i = half; i < SizeArray; i++){ //to print the second half
cout << setArray[i] << "\t";
}
cout << "\n\n\nmerge " << endl;
for (int i = 0; i < SizeArray; i++) { //to print all elements of the array
cout << setArray[i] << "\t";
}
}
example of error there should be no "4" there
我希望知道为什么元素会发生变化以及有哪些可能的解决方案。
【问题讨论】:
-
VTC 是一个错字,因为您根本没有分配索引到的数组元素
标签: c++ arrays algorithm sorting