0

我尝试制作一个程序来对数组的数字进行排序。

我已经尽力了,但是有这个问题:虽然我做了一个循环来交换数字并排列它们,但当我输出数组时,没有任何变化,数组保持不变。

代码将使一切更清晰

这是主要功能:

int main(){
int arr[10];
//For loop to get from user numbers to be put into the array
for ( int i = 0; i<10; i++){
    cout << "Enter the number to be recorded: ";
    cin >> arr[i];
    cout << endl;
}
// Set counter n to 0 ( counts numbes of number swaps)
int n = 0;
do {
    //re sets counter to 0
    n=0;

    //Check the entire loop if arr[i] bigger than arr[i+1] and swaps their values if true then adds 1 to n
    for ( int i = 0; i>9; i++){
        if(arr[i]>arr[i+1]){
            swap(&arr[i], &arr[i+1]);//swaps by sending the addresses of the two array elements the pointers in the swap function
            n++;
        }
    }
}while(n>0); // if counter = 0 then end (therefore the numbers are arranged correctly since no swapping happened)
cout << "The numbers ordered are:\n\n";
// Loop to output the arranged array
for (int i =0; i<10; i++){
    cout << arr[i] << ", ";
}
cout<<endl;
system("PAUSE");
return 0;}

这是交换功能:

void swap ( int *p, int *t){
int temp;
temp = *p;
*p = *t;
*t = temp;}

我希望你们能在这里帮助我解决我的问题并告诉我这段代码有什么问题

谢谢你们

4

2 回答 2

5

仔细查看你的 for 循环......它的内容永远不会被执行。

for ( int i = 0; i>9; i++){ ... }

条件i>9应该是i<9

于 2012-07-28T02:58:11.107 回答
1
   for ( int i = 0; i>9; i++){
                    ^^^
                     here is your problem 

您已经初始化i to the 0并检查条件是 if i is greater than 9which is not never true所以for 循环条件,因此它将被终止

它应该是

for( int i = 0; i<9; i++) than the 

结果

   i=0 condition i<9 true  { come in the function body}
   i=1 condition i<9 true  { come in the function body}
   .
   .
   .
   i=8 condition i<9 true  { come in the function body}
   i=9 condition i<9 false  { } 
于 2012-07-28T03:03:55.900 回答