C++:对数组进行排序,最后一个数字重复两次
C++: sorting an array, last number duplicated twice
我是来自基础的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;
}
相关文章:
- 找到两对数字,使它们的乘积的绝对差最小化
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- C++通过数字比较两个数字
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 我应该如何去缓解两次出现的cin?
- 在 txt 文件中显示前两个数字的程序
- Realloc 两次无法在 Visual Studio 上运行
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- C++ 检查结果数组中有多少次数字
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 连续两次写入数字时出现逻辑错误 (C++)
- C++:对数组进行排序,最后一个数字重复两次
- 如何使用Mersenne Twister生成两个数字之间的所有值一次
- 有没有办法将 int 赋入具有递归函数的字符串中,而无需将数字反转两次
- 为什么我的代码要求"请输入 2-12 之间的数字:"两次?
- c++将输出(数字)保存到一个数组中.一次两个数字