繁体   English   中英

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

[英]How does the “if block” work in this 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;
}

上面的代码产生两个插入数字中的最小值。 谁能解释 if 块是如何工作的?

这是交换两个数字的惯用方式。

有更有效的方法:利用那些使用std::swap代替。

(语句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