一些人发现此代码存在溢出问题.小的数字是非常负的

Some find of overflow issue with this code. small number is extremely negative

本文关键字:数字 非常 出问题 发现 代码 存在 溢出 一些人      更新时间:2023-10-16

这是我的代码,试图制作一个由十个数字组成的数组,并输出其中最大和最小的数字。当我运行这个时,我的较小值是一个非常大的负数:

#include <iostream>
using namespace std;
int main()
{
    int nums[10];
    int small, large;
    large = small = nums[0];
    for (int i = 0; i < 10; i++)
    {
        cout << "Enter an integer number:" << endl;
        cin >> nums[i];
    }
    for (int i = 0; i < 10; i++)
    {
        if (large < nums[i])
            large = nums[i];
    }
    for (int i = 0; i < 10; i++)
    {
        if (small > nums[i])
            small = nums[i];
    }
    cout << "The biggest number entered was " << large << ". " << endl;
    cout << "While the smallerst number entered was " << small << ". " << endl;
    system("pause");
    return 0;
}

您正在读取一个未初始化的变量:

if (large < nums[i]) // large has not been initialized here

这里是

if (small > nums[i]) // small has not been initialized here

这是未定义的行为。

从技术上讲,您已经为它们指定了一个值。但这个值本身来自一个未初始化的变量:

large = small = nums[0]; // nums has not been initialized

num[0]此处:

large = small = nums[0];
                ^^^^^^^

由于未初始化,因此具有不确定的值,因此largesmall在该赋值之后也将具有不确定值。像这里一样使用不确定值:

if (small > nums[i])

是未定义的行为,可以有任何结果。

唯一的错误是在数组num[]中有值之前分配大小。我已经编辑了你的代码,它按照你的意愿工作。

#include <iostream>

使用命名空间std;

int main(){int nums[10];int small,large;

for (int i = 0; i < 10; i++)
{
    cout << "Enter an integer number:" << endl;
    cin >> nums[i];
}
large = small = nums[0];
for (int i = 0; i < 10; i++)
{
    if (large < nums[i])
        large = nums[i];
    if (small > nums[i])
        small = nums[i];
}
cout << "The biggest number entered was " << large << ". " << endl;
cout << "While the smallerst number entered was " << small << ". " << endl;
//system("pause");
return 0;

}

更改:修复了未初始化的大小错误;删除了额外的for循环(您不需要它)删除了系统("暂停"),因为它在我的机器上导致编译错误,我认为这里没有必要。