您的位置:首页 > 其它

运算符来测试平等

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

// returns true if x and y are equal, false otherwise
bool 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。

这里是另一个例子显示的差异之间的前缀和后缀版本:
1
2
3
4
5
6
int x = 5, y = 5;
cout << x << " " << y << endl;
cout << ++x << " " << --y << endl; // prefix
cout << x << " " << y << endl;
cout << x++ << " " << y-- << endl; // postfix
cout << x << " " << y << endl;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: