簡體   English   中英

需要了解while循環條件(請參閱注釋)

[英]need understanding of while loop condition (see comment)

while (x >= 1000)
{
    cout << "M";
    x -= 1000;
}

有人可以向我解釋while循環的工作原理嗎? 我知道條件是x大於或等於1000,它將打印出“ M”。

之后的部分實際上是我不了解的,是說它將繼續從X減去一千並繼續打印直到條件為假?

是的,這正是它的作用。

大致翻譯為:

當x大於或等於1000時,執行代碼塊中的操作(一遍又一遍,直到條件失敗)

然后,代碼塊將打印M並將x設置為等於其自身的負1000。( x -= 1000x = x - 1000

假想:

x = 3000
x is greater than 1000
print M
x is set to 2000
loop resets and checks x...passes test
print M
x is set to 1000
loop resets and checks x...passes test because of = portion
print M
x is set to 0
loop resets and checks x...fails
moves to the code after the while code block
while (x >= 1000)   //x is greater than or equal to 1000
{                   //executes loop if condition true, else the statement after the loop block
    cout << "M";  // print M
    x -= 1000;    // x = x-1000
}                  //goes back to condition checking

你是對的!

x-=1000; 

實際上是

x=x-1000;

是。

它說它將繼續從X減去一千並繼續打印直到條件為假

該程序似乎是一種低效的編寫方式

x %= 1000;

這是x = x%1000 ,其中%是模數運算符。

您的代碼通過后續的減法達到相同的結果,並在x<1000時停止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM