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

C++: sorting an array, last number duplicated twice

本文关键字:两次 数字 最后一个 数组 排序 C++      更新时间:2023-10-16

我是来自基础的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;
    }

}

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

7172999321838784431//////////////////////////////////////////////////8214471727883939999

提前感谢您的帮助。

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

侧面需要注意的几件事。

  • 一开始你有一个变量int c,但你在每个 for 循环中也创建了一个名为 c 的新变量。(去掉第一个变量声明(
  • 循环条件的形式一般是< size,而不是<= last_index
  • 您可以在循环中混合前增量和后增量。选择一个(希望是预增量(
  • 不要调用变量list ,(的一个非常常见的名称(。

您通过读取 for 中的越界来调用未定义的行为,并while语句:

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

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;
}