C++ 关系运算符

学习C++ – C++关系运算符

C++提供了六个关系运算符来比较数字。

运算符 含义
< 小于
<= 小于或等于
== 等于
> 大于
>= 大于或等于
!= 不等于

例子

字符串类字符串的比较


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

上面的代码生成以下结果。


例2

使用if语句,关系运算符和等式运算符比较整数。


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

上面的代码生成以下结果。

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《C++ 关系运算符》
文章链接:https://zhuji.vsping.com/329317.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。