运算符来测试平等
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;
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;
相关文章推荐
- 四大组件之Service(一)-双子座的Service-Start Service与Bind Service
- Struts2学习笔记(1)
- 【二分图匹配】完美的牛栏
- VS内存断点
- Django中文显示
- MVP模式在Android项目中的使用
- PHP会员找回密码功能实现实例介绍
- Batch Normalization 导读
- enum枚举详解
- 如何让Ubuntu系统支持WebP图片格式
- Python 元组详解
- POI操作WORD文档,生成的新文档为空白文档 -- 待解决
- django传递数据给JS
- Solr/SolrCloud SearchHandler详解
- html 时间单位
- [BZOJ4198][Noi2015]荷马史诗
- 我所理解的设计模式
- 卸载loadrunner12.5,安装11.0遇到问题
- SICP Table
- CSS 实现导航条