-2
我正在構建一個程序,用戶輸入數字達100次,並輸入一個負整數。該程序應該對數字進行排序並將其顯示回給用戶。現在我的程序在進入排序循環時崩潰,我不知道爲什麼。插入排序崩潰我的程序
#include <iostream>
using namespace std;
void print(char nums[], int count)
{
int j;
for (j = 0; j < count; j++)
for (j = 0; j < count; j++)
cout << " " << nums[j];
cout << endl;
}
void Sort(char nums[], int count)
{
int i, j, tmp;
for (i = 1; i < count; i++) {
j = i;
while (nums[j - 1] > nums[j]) {
tmp = nums[j];
nums[j] = nums[j - 1];
nums[j - 1] = tmp;
j--;
} //end of while loop
print(nums, count);
} //end of for loop
}
int main()
{
char nums[101];
int count = 0;
cout << "Please enter between 2 and 100 intgers, ending with a negative integer.\nThe Negative will not be included in the list;\n";
for (int count = 0; count <= 100; count++) {
int temp;
cin >> temp;
if (temp < 0) {
break;
}
nums[count] = temp;
count++;
}
nums[count + 1] = '\0';
Sort(nums, count);
}
瞭解如何使用調試器並逐行瀏覽代碼並監視變量的變化。這很可能會導致你解決你的問題。 –
爲什麼把它看作一個int把它放在char []中? – ChiefTwoPencils
您在'for'循環中增加內部'count'變量兩次。從'for'循環中的'int count'重命名爲其他內容。即使'我'工作得更好。 – Kupiakos