2016-02-26 80 views
-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); 
} 
+1

瞭解如何使用調試器並逐行瀏覽代碼並監視變量的變化。這很可能會導致你解決你的問題。 –

+0

爲什麼把它看作一個int把它放在char []中? – ChiefTwoPencils

+0

您在'for'循環中增加內部'count'變量兩次。從'for'循環中的'int count'重命名爲其他內容。即使'我'工作得更好。 – Kupiakos

回答

0

至少有一個問題是您使用的是錯誤的count。在

for (int count = 0; count <= 100; count++) { 
    int temp; 
    cin >> temp; 
    if (temp < 0) { 

     break; 
    } 
    nums[count] = temp; 
    count++; 
} 

count您使用的是在宣佈for循環count。然後,使用count你在主宣稱,當你做

nums[count + 1] = '\0'; 

Sort(nums, count); 

這仍然是0

你也將會有

while (nums[j - 1] > nums[j]) { 
    tmp = nums[j]; 
    nums[j] = nums[j - 1]; 
    nums[j - 1] = tmp; 
    j--; 
} 

一個問題,因爲你永遠不會檢查是否j < 1。如果j < 1那麼你有一個負面的指標,這是未定義的行爲。