1 // 09-类型转换.cpp: 定义控制台应用程序的入口点。
2 //
3
4 #include "stdafx.h"
5 #include <iostream>
6 #include <climits>
7 using namespace std;
8
9
10 void SwitchStature();
11 void SwitchUnit();
12 void Percentage();
13 void FilterNumber();
14
15 int main()
16 {
17
18 float a = 3; //自动发生类型转换,通过赋值给float类型将int类型自动转换成float类型。
19 int b = 4.3; //直接输入的小数点都是double类型,将double类型赋值给int类型后,会省略小数点的部分。
20 //int c = 3e20; //这个数已经超出int范围,会出现错误,这个不属于类型转换范围,大的数存到小的数会有问题。
21
22 float res = 4 + 4.4;//先将4自动转换成double双精度浮点类型后再和4.4相加,再转换成float类型赋值给res。
23
24 int c = (int)23.8;//强制转换成int类型
25 cout << c << endl;
26
27 int d = int(23.8); //新的C++标准的语法,和上面的旧的C语言语法一样都能用。
28 cout << d << endl;
29
30 int e = int(b);
31
32 //auto 关键字是自动推断类型 类似C#中的var关键字
33
34 auto g = 's';
35 cout << g << endl; //使用auto关键字进行声明变量必须赋值初始化 ,否则auto不知道是什么类型。
36 auto h = 100;
37 cout << h << endl;
38
39 //auto关键字的缺点:
40 auto x = 0.0;//double类型 由于auto关键字必须通过赋值的类型确定,假如需要一个float类型,但是0.0默认是double类型。
41 auto z = 0;//int类型 假如需要一个short类型,但是0默认是int。
42
43 cout << e << endl;
44
45 int t;
46 cin >> t;//等待输入,将输入的结果保存在t中。
47
48
49 SwitchStature();
50 SwitchUnit();
51 Percentage();
52 FilterNumber();
53 return 0;
54
55 }
56
57
58 //____________________________________________练习______________________________________________________
59 //1、让用户输入自己的身高(米),然后把它转换为厘米,并输出出来。
60 //答:
61 void SwitchStature()
62
63 {
64 float height;
65 cout << "请输入自己身高(米)!" << endl;
66 cin >> height;
67 height =height*100;
68 cout << height <<"cm"<< endl;
69
70 int t;
71 cin >> t;
72 }
73
74 //2、编写一个程序,让用户输入秒,计算出一共包含多少天,多少小时,多少分钟,多少秒。
75 //答:
76 void SwitchUnit()
77 {
78 int inputSec=0;
79 int day=0;
80 int hours=0;
81 int minute=0;
82 int sec=0;
83 cout << "请输入秒" << endl;
84 cin >> inputSec;
85
86 day = inputSec/86400;
87 hours = (inputSec % 86400) / 3600;
88 minute= (inputSec % 86400%3600)/60;
89 sec = inputSec % 86400 % 3600 % 60;
90
91 cout << day << "天 " << hours << "小时 " << minute << "分钟 " << sec << "秒 " << endl;
92
93 int t;
94 cin >> t;
95 }
96
97 //3、要求用户输入一个班级的 男生和女生的数量,并输出女生的比例(百分比)
98 //答:
99
100 void Percentage()
101 {
102 int boyNum = 0;
103 int girlNum = 0;
104 float percent;
105 cout << "请输入男生数量" << endl;
106 cin >> boyNum;
107 cout << "请输入女生数量" << endl;
108 cin >> girlNum;
109 cout << "男女生分别为" << boyNum << " " << girlNum<<endl;
110 percent = (girlNum/ (boyNum + float(girlNum)))*100;
111 cout << "女生的比例为:" << percent << "%" << endl;
112
113 int t;
114 cin >> t;
115 }
116
117 //4、输入一四位个数字,分别取出这个数字每一位上的数。
118
119 void FilterNumber()
120 { //1234
121 cout << "请输入一个数字(四位数)!" << endl;
122 int num ;
123 cin >> num;
124 int ge = num % 10;
125 int shi = (num % 100) / 10;
126 int bai = (num % 1000) / 100;
127 int qian = num /1000;
128 cout << "得到的4个数字分别为:" << qian << " " << bai << " " << shi << " " << ge << endl;
129
130 int t;
131 cin >> t;
132 }