You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++冒泡排序程序异常:无法输入最后元素且出现垃圾值

问题与解决:C++冒泡排序程序输入异常

问题现象

程序本应接收指定数量的数字并升序排序,但输入到倒数第二个数字后程序就结束,最后一个元素位置显示垃圾值(如-858993460)。

错误原因

输入循环的条件错误:原代码中输入循环写的是for (y = 0; y < (x - 1); y++),这意味着只会读取x-1个数字,数组的最后一个元素arry[x-1]从未被赋值,保留了内存中的随机垃圾值。

修正方案

  • 修改输入循环条件:将输入循环的终止条件从y < (x - 1)改为y < x,确保能读取到全部x个数字。
  • 优化提示文本:将cout << "Please enter " << x << "numbers\n";中的"numbers"前加空格,变成" numbers",让提示语更通顺。

修正后的完整代码

#include<iostream>
using namespace std;
int main()
{
    int x, y, arry[61], z, interim;
    cout << "Please enter how many numbers you would like to sort:\n>> ";
    cin >> x;
    cout << "Please enter " << x << " numbers\n";
    // 修正输入循环条件,确保读取x个数字
    for (y = 0; y < x; y++)
        cin >> arry[y];
    cout << "Give bubble sort a minute to do its thing.....";
    for (y = 0; y < (x - 1); y++)
    {
        for (z = 0; z < (x - y - 1); z++)
        {
            if (arry[z] > arry[z + 1])
            {
                interim = arry[z];
                arry[z] = arry[z + 1];
                arry[z + 1] = interim;
            }
        }
    }

    cout << "\nBubble sorted as went through the array in accending order\n Arry:";
    for (y = 0; y < x; y++)
        cout << arry[y] << " ";
    cout << endl;
    return 0;
}

额外说明

  • 数组大小修改不影响这个问题,因为问题根源是输入数量不足,而非数组容量不够。
  • 垃圾值-858993460是Windows系统中未初始化int变量的默认值(对应十六进制的0xCCCCCCCC)。

内容的提问来源于stack exchange,提问作者InternetHateMachine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:05:19