fqy131314

C++项目练习(1)

练习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

理解:

 

posted on   会飞的鱼-blog  阅读(22)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示