练习1-数学计算
让用户输入一个圆的半径,计算这个圆的周长和面积,并输出(保留两位小数)
#include <iostream> #include <Windows.h> int main(void) { float r; float len; float s; std::cout << "请输入半径:"; std::cin >> r; len = 2 * 3.14 * r; s = 3.14 * r * r; std::cout.precision(2); std::cout.flags(std::cout.fixed); std::cout << "周长是:" << len << std::endl; std::cout << "面积是: " << s << std::endl; system("pause"); return 0; }
练习2-无符号数的诡异
#include <iostream> #include <Windows.h> using namespace std; int main(void) { unsigned boyAge; unsigned girlAge; unsigned diff; cout << "美女,多大了?" << endl; cin >> girlAge; //输入25 cout << "帅哥,多大了?" << endl; cin >> boyAge; //输入22 diff = girlAge - boyAge; cout << "美女比帅哥大" << diff <<"岁" << endl; diff = boyAge - girlAge; cout << "帅哥比美女大" << diff << "岁" << endl; system("pause"); return 0; }
执行结果:
说明:unsigned 类型,就是unsigned int
分析:
在尾部添加如下代码:
unsigned short boyAge2 = boyAge; unsigned short girlAge2 = girlAge; unsigned short diff2 = boyAge2 - girlAge2; cout << "帅哥比美女大" << diff2 << "岁" << endl; //输出65533
结论:
无符号数,不能表示负数!
如果强行用无符号数表示负数,实际存储的是这个负数对应的“补码”
即:该负数 + “模值”
-3 + 65536 = 65533
理解: