C++ 关系运算符
2018-03-24 14:42 更新
学习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;
}
上面的代码生成以下结果。
以上内容是否对您有帮助:
更多建议: