2016-02-26 83 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那么你有一个负面的指标,这是未定义的行为。