W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
C++具有五個基本算術(shù)運算的運算符:加法,減法,乘法,除法和取模。
這些運算符中的每一個使用兩個稱為操作數(shù)的值來計算最終答案。
一起,運算符及其操作數(shù)構(gòu)成一個表達式。
例如,考慮以下語句:
int result = 4 + 2;
值4和2是操作數(shù),+符號是加法運算符,4 + 2是一個值為6的表達式。
這里是C++的五個基本算術(shù)運算符:
% 運算符僅使用整數(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é)果。
除法運算符(/)的行為取決于操作數(shù)的類型。
如果兩個操作數(shù)都是整數(shù),則C++執(zhí)行整數(shù)除法。
這意味著答案的任何小數(shù)部分被丟棄,使結(jié)果成為整數(shù)。
如果一個或兩個運算符數(shù)是浮點值,則保留小數(shù)部分,使結(jié)果浮點。
以下代碼說明了C++部分如何與不同類型的值一起使用。
#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é)果。
模運算符返回整數(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)看到兩個:增量運算符(++),和減量運算符(--)。
每個運算符有兩個種類。
前綴版本在運算符之前,如在++x中。
后綴版本在運算符之后,如在x++中。
這兩個版本對運算符具有相同的效果,但它們在何時發(fā)生時有所不同。
以下代碼演示了增量運算符的這種差異。
#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++意味著“在評估表達式中使用當(dāng)前值a,然后增加a的值”。
++b表示“首先遞增b的值,然后在評估表達式時使用新值?!?/span>
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: