一些人发现此代码存在溢出问题.小的数字是非常负的
Some find of overflow issue with this code. small number is extremely negative
这是我的代码,试图制作一个由十个数字组成的数组,并输出其中最大和最小的数字。当我运行这个时,我的较小值是一个非常大的负数:
#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];
^^^^^^^
由于未初始化,因此具有不确定的值,因此large
和small
在该赋值之后也将具有不确定值。像这里一样使用不确定值:
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循环(您不需要它)删除了系统("暂停"),因为它在我的机器上导致编译错误,我认为这里没有必要。
相关文章:
- 使用浮点数和双精度数的非常小数字的数学
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 具有非常非常大数字的算术运算
- 如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法
- 如何找到由公式计算的非常大的数字的最后一位数字?
- 找到非常大的数字的最右边的未设置位
- 在C++中使用限制和非常大的数字时出现问题
- C 非常奇怪的数字
- 在不使用递归的情况下将 FFT 应用于两个非常大的数字的乘法
- C++整数除法给出非常大的数字
- 在不进行线性搜索的情况下,在非常大的数组中找到比给定数字更小的数字
- 两个非常大的数字的乘积的第一个数字
- 找到非常大数字的分裂模型
- 在非常大的数字序列中查找句点
- 如何在 c++ 中存储非常大的数字
- 查找非常大的 2^n 数字的最后一位数字
- 将十进制转换为二进制,并计算其中的数字非常非常大
- 在GTest中,如何检查数字非常接近0?EXPECT_FLOAT_EQ不工作
- 输出文件中显示的数字非常大
- 数字的组成,其中数字非常大