运算符来测试平等

来源:互联网 发布:最流行的编程语言 编辑:程序博客网 时间:2024/04/29 12:35

布尔值也很有用,作为返回值的函数,检查是否是真实的或不。这样的功能通常开始以“字(如平等)或(如hascommonfactor)。在下面的例子中,我们使用相等操作符(= =)来测试,如果值是相等的。如果操作数是相等的,则运算符=返回真值,如果它们不是。值得注意的是,在C++中,一个单一的等于(=)是一个赋值运算符,而双等号(= =)是一个比较运算符来测试平等

12345678910111213141516171819202122232425#include <iostream> // returns true if x and y are equal, false otherwisebool isEqual(int x, int y){    return (x == y); // operator== returns true if x equals y, and false otherwise} int main(){    std::cout << "Enter an integer: ";    int x;    std::cin >> x;     std::cout << "Enter another integer: ";    int y;    std::cin >> y;     bool equal = isEqual(x, y);    if (equal)        std::cout << x << " and " << y << " are equal" << std::endl;    else        std::cout << x << " and " << y << " are not equal" << std::endl;    return 0;}

让我们来看看这条线是如何工作的更详细。首先,编译器将一个具有相同值的临时副本复制为5。然后,它将原来的×从5增加到6。然后,编译器将计算结果为5,并将该值赋给Y,然后将临时副本丢弃。
因此,结束时的值为5,和*结束的值6。
这里是另一个例子显示的差异之间的前缀和后缀版本:

123456int x = 5, y = 5;cout << x << " " << y << endl;cout << ++x << " " << --y << endl; // prefixcout << x << " " << y << endl;cout << x++ << " " << y-- << endl; // postfixcout << x << " " << y << endl;


0 0
原创粉丝点击