为什么给unsigned赋负数,运算可以继续?

来源:百度知道 编辑:UC知道 时间:2024/09/28 06:43:15
刚学C++,今天看了变量类型,编了个小程序:
#include <iostream>

int main()
{
using std::cout;
using std::cin;
using std::endl;

unsigned short Width;
unsigned short Length;
unsigned short Area;

cout << "Now, let's calculate the Area when the Width and the Length are defined...\n";
cout << endl;
cout << "First, input the Width:\t\t\t";
cin >> Width;
cout << "Second, input the Length:\t\t";
cin >> Length;
cout << endl;
cout << "Then, the computer gives the Area:\t";
Area = Width * Length;
cout << Area;
cout << endl << endl << endl;

return 0;
}

正如大家所见,主函数一开始我便指明三个变量都是unsigned。在运行的时候我试着输入了负数,本以为程序不会继续运行,没想到,输入一个负数,结果是一个巨大的正数(一般是六万多),输入两个负数,就直接出来它们的积了。请问这是怎么回事呢?
谢谢!
那为什么输入两个负数结果又对了呢?

有符号的整数在存储时用最高位表示符号,比如1表示负,0表示正;无符号整数在存储时没有符号位,如果输入负数,最高位是1,再转换成10进制数的时候这个1就不代表符号了

一楼说得没错!