C++ 關(guān)系運(yùn)算符

2018-03-24 14:42 更新

學(xué)習(xí)C++ - C++關(guān)系運(yùn)算符

C++提供了六個(gè)關(guān)系運(yùn)算符來(lái)比較數(shù)字。

運(yùn)算符含義
<小于
<=小于或等于
==等于
>大于
>=大于或等于
!=不等于

例子

字符串類字符串的比較


#include <iostream>
#include <string>     // string class
int main()
{
    using namespace std;
    string word = "?ate";

    for (char ch = "a"; word != "mate"; ch++)
    {
        cout << word << endl;
        word[0] = ch;
    }
    cout << "After loop ends, word is " << word << endl;
    // cin.get();
    return 0; 
}

上面的代碼生成以下結(jié)果。


例2

使用if語(yǔ)句,關(guān)系運(yùn)算符和等式運(yùn)算符比較整數(shù)。


#include <iostream> // allows program to perform input and output 

using std::cout; // program uses cout 
using std::cin; // program uses cin 
using std::endl; // program uses endl 

int main() { 
    int number1; // first integer to compare 
    int number2; // second integer to compare 

    cout << "Enter two integers to compare: "; // prompt user for data 
    cin >> number1 >> number2; // read two integers from user 

    if ( number1 == number2 ) 
        cout << number1 << " == " << number2 << endl; 

    if ( number1 != number2 ) 
        cout << number1 << " != " << number2 << endl; 

    if ( number1 < number2 ) 
        cout << number1 << " < " << number2 << endl; 

    if ( number1 > number2 ) 
        cout << number1 << " > " << number2 << endl; 

    if ( number1 <= number2 ) 
        cout << number1 << " <= " << number2 << endl; 

    if ( number1 >= number2 ) 
        cout << number1 << " >= " << number2 << endl; 
}

上面的代碼生成以下結(jié)果。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)