这两个程序有什么不同

What is the difference between these two programs?

本文关键字:什么 程序 两个      更新时间:2023-10-16

这两个程序之间有什么区别?第一个程序的输出为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();
}

在第一个代码块中,您将输出x,然后将其相加,这样它将输出0-9。在第二个代码块中,在输出之前将1添加到x,这样它将为您提供1-10的输出。它基于x++相对于输出语句

的位置

第一个的输出为0 1 2 3 4 5 6 7 8 9。第二个输出是1 2 3 4 5 6 7 8 9 10。

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

这显然是由于订单的原因。在第一个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

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

第二个代码段递增变量,然后打印它。这意味着它不会打印0。它被初始化为.

的值