简体   繁体   English

同时构造对整数进行排序[C ++]

[英]while Construct to Sort ints [C++]

can anyone tell me why this doesn't work? 谁能告诉我为什么这行不通? I'm trying to sort five ints using a while loop, but the output is only giving me the numbers I entered in the order I entered them. 我正在尝试使用while循环对五个整数进行排序,但输出仅按顺序输入了我输入的数字。 I'm very new to programming, and I really have no idea what I'm doing. 我对编程非常陌生,我真的不知道自己在做什么。

Here is my code: 这是我的代码:

#include <iostream>
using namespace std;

    int main()
    {
        int n1, n2, n3, n4, n5, temp, i;

        cout << "Enter five numbers to be sorted: " <<'\n';
        cin >> n1 >> n2 >> n3 >> n4 >> n5;

        while(i<4) { 
        i++;
                  if(n1>n2) {
                  temp = n1;
                  n1 = n2; 
                  n2 = temp;
                  }
                  if(n2>n3) {
                  temp = n2;
                  n2 = n3;
                  n3 = temp;
                  }
                  if(n3>n4) {
                  temp = n3;
                  n3 = n4;
                  n4 = temp;
                  }
                  if(n4>n5) {
                  temp = n4;
                  n4 = n5;
                  n5 = temp;
                  }
                  }
                  cout << n1 << " " << n2 << " " << n3 << " " << n4 << " " << n5 << endl;
                  system("PAUSE");
                  return(0);
    }

You never initialized i so it causes undefined behaviour to test i<4 ; 您从未初始化过i所以它导致不确定的行为来测试i<4 probably this causes the loop to never be entered. 可能这将导致永远不会进入循环。

Change the loop to for (int i = 0; i < 4; ++i) and take out the earlier definition of i . 改变循环到for (int i = 0; i < 4; ++i)和取出的早期定义i

Of course, the sorting logic can be improved a lot by the use of containers instead of having five separate int variables! 当然,可以通过使用容器而不是五个独立的int变量来大大改善排序逻辑!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM