C++具有五個(gè)基本算術(shù)運(yùn)算的運(yùn)算符:加法,減法,乘法,除法和取模。
這些運(yùn)算符中的每一個(gè)使用兩個(gè)稱(chēng)為操作數(shù)的值來(lái)計(jì)算最終答案。
一起,運(yùn)算符及其操作數(shù)構(gòu)成一個(gè)表達(dá)式。
例如,考慮以下語(yǔ)句:
int result = 4 + 2;
值4和2是操作數(shù),+符號(hào)是加法運(yùn)算符,4 + 2是一個(gè)值為6的表達(dá)式。
這里是C++的五個(gè)基本算術(shù)運(yùn)算符:
% 運(yùn)算符僅使用整數(shù)。
以下代碼執(zhí)行一些C ++算術(shù)。
#include <iostream>
using namespace std;
int main()
{
float hats, my_head;
cout.setf(ios_base::fixed, ios_base::floatfield); // fixed-point
cout << "Enter a number: ";
cin >> hats;
cout << "Enter another number: ";
cin >> my_head;
cout << "hats = " << hats << "; my_head = " << my_head << endl;
cout << "hats + my_head = " << hats + my_head << endl;
cout << "hats - my_head = " << hats - my_head << endl;
cout << "hats * my_head = " << hats * my_head << endl;
cout << "hats / my_head = " << hats / my_head << endl;
return 0;
}
上面的代碼生成以下結(jié)果。
除法運(yùn)算符(/)的行為取決于操作數(shù)的類(lèi)型。
如果兩個(gè)操作數(shù)都是整數(shù),則C++執(zhí)行整數(shù)除法。
這意味著答案的任何小數(shù)部分被丟棄,使結(jié)果成為整數(shù)。
如果一個(gè)或兩個(gè)運(yùn)算符數(shù)是浮點(diǎn)值,則保留小數(shù)部分,使結(jié)果浮點(diǎn)。
以下代碼說(shuō)明了C++部分如何與不同類(lèi)型的值一起使用。
#include <iostream>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "Integer division: 9/4 = " << 9 / 4 << endl;
cout << "Floating-point division: 9.0/4.0 = ";
cout << 9.0 / 4.0 << endl;
cout << "Mixed division: 9.0/4 = " << 9.0 / 4 << endl;
cout << "double constants: 1e7/9.0 = ";
cout << 1.e7 / 9.0 << endl;
cout << "float constants: 1e7f/9.0f = ";
cout << 1.e7f / 9.0f << endl;
return 0;
}
上面的代碼生成以下結(jié)果。
模運(yùn)算符返回整數(shù)除法的余數(shù)。
以下代碼使用%操作符將lbs轉(zhuǎn)換為stone。
#include <iostream>
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";
return 0;
}
上面的代碼生成以下結(jié)果。
你已經(jīng)看到兩個(gè):增量運(yùn)算符(++),和減量運(yùn)算符(--)。
每個(gè)運(yùn)算符有兩個(gè)種類(lèi)。
前綴版本在運(yùn)算符之前,如在++x中。
后綴版本在運(yùn)算符之后,如在x++中。
這兩個(gè)版本對(duì)運(yùn)算符具有相同的效果,但它們?cè)诤螘r(shí)發(fā)生時(shí)有所不同。
以下代碼演示了增量運(yùn)算符的這種差異。
#include <iostream>
using std::cout;
int main(){
int a = 20;
int b = 20;
cout << "a = " << a << ": b = " << b << "\n";
cout << "a++ = " << a++ << ": ++b = " << ++b << "\n";
cout << "a = " << a << ": b = " << b << "\n";
return 0;
}
a++意味著“在評(píng)估表達(dá)式中使用當(dāng)前值a,然后增加a的值”。
++b表示“首先遞增b的值,然后在評(píng)估表達(dá)式時(shí)使用新值。”
上面的代碼生成以下結(jié)果。
更多建議: