运算符
#include<iostream>
int main()
{
using namespace std;
float a = 56.14;
float b = 2.15;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << a << endl;
cout << b<< endl;
cout << a + b<< endl;
cout << a - b << endl;
cout << a * b << endl;
cout << a / b << endl;
return 0;
}
56.139999
2.150000
58.290001
53.989998
120.701004
26.111626
可以看到,56.14在内存里存储的并不一定是精确的56.14,所以浮点数的运算会有一定的精度误差,如果精度要求很高,可以用double,long double
优先级
类型转换
#include<iostream>
int main()
{
using namespace std;
float a = 56;
int b = 2.15e18; //超出了int得到表示范围,则结果是不确定的,这里我的编译器把这种不确定值显示为int的最大值
int c = 2.15;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << a << endl;
cout << b << endl;
cout << c << endl;
return 0;
}
56.000000
2147483647
2
大括号初始化中的类型转换
#include<iostream>
int main()
{
using namespace std;
char ch{128};
cout << ch << endl;
return 0;
}
编译会报警告, narrowing conversion, 大括号的列表初始化是不允许这种缩窄初始化的,因为这个类型表示不了这个值
显示的结果,不是ascii 字符,可能是别的字符集,不明白
€
改为char ch{63}; 就不警告,正常显示问号
?
把变量放在大括号里初始化,也可以的,和书上讲的不一样诶
#include<iostream>
int main()
{
using namespace std;
int x = 63;
char ch{x};
cout << ch << endl;
return 0;
}
超出范围初始化,结果不确定
}
强制转换
auto声明
还不明白,后面补充
第三章习题
欧洲: 升/公里
美国: 英里/加仑 miles per gallon mpg
12.4—>19 8.7—>127
所以首先要把输入的欧洲的升x转换为加仑,除以3.875, x/3.875;
再除以64.14, x /3.875/62.14 加仑/英里
求倒数即可
#include<iostream>
int main()
{
using namespace std;
float europe;
cout << "Enter the oil consumption in European style. (litre/km)" << endl;
cin >> europe;
cout << "The corresponding value in American style (mile/gallon) is : " << 1/(europe/3.875/62.14) << endl;
return 0;
}
Enter the oil consumption in European style. (litre/km)
12.4
The corresponding value in American style (mile/gallon) is : 19.4188