国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

C++ 算術運算符

2018-03-24 14:36 更新

學習C++ - C++算術運算符

C++具有五個基本算術運算的運算符:加法,減法,乘法,除法和取模。

這些運算符中的每一個使用兩個稱為操作數的值來計算最終答案。

一起,運算符及其操作數構成一個表達式。

例如,考慮以下語句:

int result = 4 + 2;

值4和2是操作數,+符號是加法運算符,4 + 2是一個值為6的表達式。

這里是C++的五個基本算術運算符:

  • + 運算符添加其操作數。
  • - 運算符從第一個運算符中減去第二個操作數。
  • * 運算符乘以其操作數。
  • / 運算符將其第一個操作數除以第二個。
  • % 運算符產生將第一個除以第二個的余數。

% 運算符僅使用整數。


例子

以下代碼執(zhí)行一些C ++算術。


#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; 
} 

上面的代碼生成以下結果。

除法運算符

除法運算符(/)的行為取決于操作數的類型。

如果兩個操作數都是整數,則C++執(zhí)行整數除法。

這意味著答案的任何小數部分被丟棄,使結果成為整數。

如果一個或兩個運算符數是浮點值,則保留小數部分,使結果浮點。

以下代碼說明了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; 
} 

上面的代碼生成以下結果。

模運算符

模運算符返回整數除法的余數。

以下代碼使用%操作符將lbs轉換為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; 
} 

上面的代碼生成以下結果。

遞增(++)和遞減( -- )運算符

你已經看到兩個:增量運算符(++),和減量運算符(--)。

每個運算符有兩個種類。

前綴版本在運算符之前,如在++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++意味著“在評估表達式中使用當前值a,然后增加a的值”。

++b表示“首先遞增b的值,然后在評估表達式時使用新值。”

上面的代碼生成以下結果。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號