我是来自基础的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
提前感谢您的帮助。
答案 0 :(得分:3)
您声明了一个大小为9的数组,但您需要10个元素。要修复,请将数组的声明更改为int list[10];
旁边需要注意的一些事项。
int c
,但您也在每个名为c
的for循环中创建了一个新变量。 (摆脱第一个变量声明)< size
形式,而不是<= last_index
。list
,(类的一个非常常见的名称)。答案 1 :(得分:3)
您通过阅读for
和while
声明中的界限来调用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;
}