C++心得笔记
C++ Primer Plus 第三章 处理数据
3.4 C++算术运算符
C++提供几种运算符来完成5种基本的算术计算:加法、减法、乘法、除法以及求模。每种运算符都是用到了两个值(操作数)来计算结果。运算符及其操作数构成了表达式。
- +运算符对操作数执行加法运算。
- -运算符从第一个数中减去第二个数。
- *运算符将操作数相乘。
- /运算符用第一个数除以第二个数。
- %运算符求模。(两个操作数必须都是整型,将该运算符用于浮点将导致编译错误)
#include<iostream> #include<stdlib.h> int main() { using namespace std; float hats, heads; cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point cout << "Enter a number: "; cin >> hats; cout << "Enter another number: "; cin >> heads; cout << "hats = " << hats << "; heads = " << heads << endl; cout << "hats + heads = " << hats + heads << endl; cout << "hats - heads = " << hats - heads << endl; cout << "hats * heads = " << hats * heads << endl; cout << "hats / heads = " << hats / heads << endl; system("pause"); return 0; }
可能有些人会觉得运算结果心存怀疑。11.17加上50.25应等于61.42,但是输出中却是61.419998.这不是运算问题;而是由于float类型表示有效位数的能力有限。因为对于float,C++只保证6位有效位。如果将6.419998四舍五入成6位,将得到6.4200,这是保证精度下的正确值。如果需要更高的精度,请使用double或long double。
若求模运算中两个操作数有一个不是整型,则出现以下情况,编译器报错。
![]()
3.4.1 运算符优先级和结合性
算术运算符遵循通常的代数优先级,先乘除,后加减。当两个运算符的优先级相同时,C++将看操作数的结合性(associativity)是从左到右,还是从右到左。从左到右的结合性意味着如果两个优先级相同的运算符被同时用于同一个操作数,则首先应用于左侧的运算符。从右向左的结合性则首先应用于右侧的运算符。
3.4.2 除法分支
除法运算符(/)的行为取决于操作数的类型。如果两个操作数都是整数,则C++将执行整数除法。这意味着结果的小树部分将被丢弃,使得最后的结果是一个一个整数。如果其中有一个(或两个)操作数是浮点值,则小数部分将保留,结果为浮点数。
#include<iostream>
#include<stdlib.h>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "Inter division: 9/5 = " << 9 / 5 << endl;
cout << "Floating_point division: 9.0/5.0 = " << 9.0 / 5.0 << endl;
cout << "Mixed division: 9.0/5 = " << 9.0 / 5 <<endl;
cout << "double constants: 1e7/9.0 = " << 1.e7 / 9.0 <<endl;;
cout << "float constants: 1e7/9.0f = " << 1.e7f / 9.0f <<endl;
system("pause");
return 0;
}
3.4.3 求模运算符
求模运算符返回整数除法的余数。它与整数除法相结合。
#include<iostream>
#include<stdlib.h>
int main()
{
using namespace std;
const int Lbs_per_stn = 14;
int lbs;
cout << "Enter your weight in pounds: ";
cin >> lbs;
int stone = lbs / Lbs_per_stn; // whole stone
int pounds = lbs % Lbs_per_stn; // remainder in pounds
cout << lbs << " pounds are " << stone << " stone, " << pounds << "pound(s).\n";
system("pause");
return 0;
}