【发布时间】:2012-05-27 02:16:48
【问题描述】:
到目前为止,我有这个代码。当我将两个负整数相加时,答案是肯定的而不是否定的。我该如何解决? 我认为 0x80000000 是整数的最小可能值
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
unsigned int maxInt = 0x7FFFFFFF;
int num1 = 7;
signed int minInt = 0x80000000;
int num2 = -21;
float num3 = 1;
float i;
cout<<"The value of the first variable is: "<<maxInt<<endl;
cout<<"The value of the second variable is: "<< num1<<endl;
cout<<"Addition of the two numbers: "<< maxInt + num1 <<endl;
cout<<endl;
cout<<"The value of the first variable is: "<<minInt<<endl;
cout<<"The value of the second variable is "<<num2<<endl;
cout<<"Addition of the two numbers: "<< minInt + num2 <<endl;
cout<<endl;
system("pause");
return 0;
}
【问题讨论】:
-
输出是什么?你期望它是什么?
-
你不修复它,将负数添加到
minInt会产生超出范围的结果,加法溢出,这是未定义的行为。 -
minInt的任何减法都将导致下溢,这将表示为一个正数。你不能用ints 解决这个问题,因为没有足够的位。您需要一个具有更多位的数据类型(例如longlong)。 -
你翻身了。这是人们使用固定宽度整数表示的症结所在。你如何解决它?使用较小的数字或增加用于表示这些数字的位数(例如 long)。
-
当你取最大可能的整数并将一个正整数添加到该值时,它应该环绕到最大的最小整数并从那里倒数?我得到的结果是 2147483654,因为 2147483647 是可能的最大整数