简体   繁体   English

“if 块”在这段代码中是如何工作的?

[英]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的原始值。因此,整体效果是交换ab的值。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM