[英]How does the “if block” work in this code?
Please consider the following code:请考虑以下代码:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
int a, b;
cout << "Enter two integer: ";
cin >> a >> b;
if (a > b) {
int temp = a;
a = b;
b = temp;
}
cout << a << "<=" << b << endl;
}
The above code yields the minimum of the two inserted numbers.上面的代码产生两个插入数字中的最小值。 Can anyone explain how the if block works?
谁能解释 if 块是如何工作的?
It's the idiomatic way of swapping two numbers.这是交换两个数字的惯用方式。
There are more efficient ways: to exploit those use std::swap
instead.有更有效的方法:利用那些使用
std::swap
代替。
(The statement int temp=a;
sets the variable temp
to the value of a
. The statement a=b;
sets a
to the value of b
. Finally, b=temp;
sets b
to temp
which was the original value of a
. The overall effect therefore is to exchange the values of a
and b
.) (语句
int temp=a;
将变量temp
设置为a
的值。语句a=b;
将a
设置为b
的值。最后, b=temp;
将b
设置为temp
,这是a
的原始值。因此,整体效果是交换a
和b
的值。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.