到目前爲止我有這個代碼。當我添加兩個負整數時,答案是肯定的而不是負數。我該如何解決? 我想爲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'的任何減法都會導致下溢,這將表示爲正數。由於沒有足夠的位,因此無法用「int」修復此問題。你需要一個數據類型(比如'longlong'),它有更多的位。 –