你好,我是一名新手,请告诉我是否有任何错误,下一次我会尽力改进。
我正试图理解C++中的下溢和上溢。我的理解是如果变量的范围超出了其最大值或最小值,它将从范围的另一端开始。因此,如果short的最小值为-32768,并且我们对其进行-1操作,则新值应为SHRT_MAX。(32767) 以下是我的代码:
#include<iostream.h>
#include<limits.h>
#include<conio.h>
int main ( void )
{
int testpositive =INT_MIN ;
short testnegative = SHRT_MIN ;
cout<< SHRT_MIN<<"\n";
cout << testnegative-1<<"\n";
cout << INT_MIN << "\n";
cout << testpositive-1 << "\n";
cout<<testpositive-2;
getch();
return 0;
}
int
,因此没有溢出。考虑将结果强制转换回短整型以查看您所希望的内容。 - Hans Passant#include <iostream>
而不是#include <iostream.h>
。 - L. F.