这两个程序有什么区别?

时间:2016-04-28 20:21:11

标签: c++

这两个程序有什么区别?对于第一个程序,我得到了9的输出,对于第二个程序,我得到了10的输出。

#include <iostream>

using namespace std; // So we can see cout and endl

int main()
{
    int x = 0; // Don't forget to declare variables

    while ( x < 10 ) { // While x is less than 10
        cout << x << endl;
        x++; // Update x so the condition can be met eventually
    }
    cin.get();
}
#include <iostream>

using namespace std; // So we can see cout and endl

int main()
{
    int x = 0; // Don't forget to declare variables

    while ( x < 10 ) { // While x is less than 10
        x++; // Update x so the condition can be met eventually
        cout << x << endl;
    }
    cin.get();
}

5 个答案:

答案 0 :(得分:4)

在第一个代码块中输出x然后添加到它,这样它将输出0-9。在第二个代码块中,在输出之前将x加1,这样它就会给出输出1-10。它基于您将x++放在与输出语句相关的位置

答案 1 :(得分:3)

第一个输出为0 1 2 3 4 5 6 7 8 9.秒输出为1 2 3 4 5 6 7 8 9 10.

答案 2 :(得分:1)

在第一个例子中,你写出数字然后增加变量,而在第二个例子中,你首先增加数值。

答案 3 :(得分:0)

这是由于订单(显然)。在第一个while循环中,当x为9时,它会打印它,增加它并且不通过条件并且不会再次进入循环。

在第二种情况下,当x为9时,它会将其增加到10然后打印它,然后离开循环。这只是常识。因此,第二个循环跳过数字0,并打印到10。

第一次循环:0,1,2,3,4,5,6,7,8,9

第二次循环:1,2,3,4,5,6,7,8,9,10

答案 4 :(得分:0)

第一个片段打印变量的值,然后递增它。这意味着不会打印最后一次递增后的变量值。

第二个片段会递增变量,然后将其打印出来。这意味着它不会打印0.它初始化为的值。

相关问题