一些发现此代码的溢出问题。少数是非常消极的

时间:2013-11-20 19:18:23

标签: c++ arrays numbers overflow undefined-behavior

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

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

3 个答案:

答案 0 :(得分:2)

您正在阅读未初始化的变量:

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

答案 1 :(得分:0)

num[0]此处:

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

具有不确定的值,因为它未初始化,因此largesmall在此分配后也将具有不确定的值。像你这样使用不确定的值:

if (small > nums[i])

undefined behavior,可以有任何结果。

答案 2 :(得分:0)

唯一的错误是在数组num []中有值之前分配小和大。 我已经编辑了你的代码,它就像(我认为)你想要的那样工作。

#include <iostream>

使用namespace 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;

}

的变化: 修复了未初始化的大小错误; 删除额外的循环(你不需要它) 删除系统(“暂停”),因为它导致我的机器上的错误编译,我不认为这里需要它。