C ++:对数组进行排序,最后一个数字重复两次

时间:2018-02-05 15:54:11

标签: c++ arrays sorting

我是来自基础的C ++新手,我在排序数组时遇到了麻烦。目的是生成10个随机数,然后对它们进行排序,但最后一个数字似乎重复了两次。我已经尝试了所有不同类型的循环,但我似乎无法弄清楚为什么会发生这种情况。

#include <iostream>
#include <time.h>
#include <cmath>
#include <stdlib.h>

int main(){
    int c,x;
    x = 1;
    int swap1, swap2;
    int list [9];
    srand(time(NULL));

    for (int c = 0; c <= 9; c++){
          list [c] = rand() % 100 + 1;
         std::cout << list[c] << std::endl;

    }

    while(x <= 9){

        for(int c = 0; c <=9;++c){

            if(list[c] > list[x]){
            swap1 = list[c];
            swap2 = list[x];
            list[x] = swap1;
            list[c] = swap2;

        }

    }
    x = x + 1;
    }

    std::cout << "//////////////////////////////////////////////////" << std::endl;

      for (int c = 0; c <= 9; c++){

         std::cout << list[c] << std::endl;

    }


}

这是输出。在///////的左边是生成的随机数,在行的右边是排序后的数组。问题是最后一个数字重复两次,并且缺少一个数字。

71 72 99 93 21 83 8 78 44 31 ////////////////////////////////////////////////// 8 21 44 71 72 78 83 93 99 99

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您声明了一个大小为9的数组,但您需要10个元素。要修复,请将数组的声明更改为int list[10];

旁边需要注意的一些事项。

  • 您在开头有一个变量int c,但您也在每个名为c的for循环中创建了一个新变量。 (摆脱第一个变量声明)
  • 循环条件通常采用< size形式,而不是<= last_index
  • 您在循环中混合前后增量。选择一个(希望预增量)
  • 请勿调用变量list,(的一个非常常见的名称)。

答案 1 :(得分:3)

您通过阅读forwhile声明中的界限来调用undefined behavior

for (int c = 0; c <= 9; c++) {
    list[c] = rand() % 100 + 1; // UB!

也在

while (x <= 9) {
    for (int c = 0; c <= 9; ++c) {
        if (list[c] > list[x]) { // UB!

但是在这一点上它并不重要,因为之前已经调用了UB。 C ++中的数组是零索引的,因此当c变为9时,程序会调用UB。将您的数组声明更改为:

int list[10];

或者将您的上边界更改为小于9,而不是小于或等于9

答案 2 :(得分:2)

Arnav Borborah的回答显示了如何将代码修复为使用std :: cout的C程序。我赞成他的答案,因为它显示了错误的位置。这是C ++方式:

#include <iostream>
#include <time.h>
#include <algorithm>

int main() {
    const size_t size = 10;
    int list[size];
    srand(static_cast<unsigned>(time(nullptr)));

    for (auto &v: list) {
        v = rand() % 100 + 1;
        std::cout << v << " ";
    }
    std::cout << std::endl;
    std::sort(std::begin(list), std::end(list));

    for (auto v : list) {
        std::cout << v << " ";
    }

    std::cout << "//////////////////////////////////////////////////" << std::endl;
}