誰能向我解釋為什么它列印 32 以及它是如何作業的整體概念?
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
uj5u.com熱心網友回復:
適當的縮進會讓它更清楚:
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
所以會發生以下情況:
a初始化為1. 我不知道為什么這個變數存在,因為它從未使用過。for執行其初始化陳述句,printf("3");。這列印3.for評估其重復條件,printf("2")。這將列印2并回傳已列印的字符數,即1.- 由于條件為真,它進入回圈體。
- 身體執行
return 0;。這從 回傳main(),從而結束回圈。
由于回圈結束,我們從不計算更新運算式printf("1"),因此它從不列印1。我們沒有得到任何重復。
uj5u.com熱心網友回復:
要知道,如果沒有無限回圈,程式從函式 main() 的左側“{”開始運行,到函式 main() 右側的“}”結束。
如您的代碼所示,您的難點在于理解 C 語言 for 回圈的流程圖。
如您所見,for 回圈的語法是:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
for loop body;
}
for 回圈如何作業?
1.初始化陳述句只執行一次。
2.然后,評估測驗運算式。如果測驗運算式的計算結果為 false,則 for 回圈終止。
3. 但是,如果測驗運算式的計算結果為真,則執行 for 回圈體內的陳述句,并更新更新運算式。
4.再次評估測驗運算式。
這個程序一直持續到測驗運算式為假。當測驗運算式為假時,回圈終止。
所以,for回圈流程圖

首先,以您的代碼為例:
#include <stdio.h>
int main(){
for (printf ("3"); printf("2"); printf("1")) break;
return 0;
}
輸出
32
1.initialization 是" printf ("3")",然后,列印:
3
2. 測驗運算式" printf("2")",總是正確的,所以列印:
2
3.for body 回圈" break",表示結束 for 回圈的執行,
不執行更新后的運算式“ printf("1")”
also, the program jump out of the for loop, and jump to "return 0;",
then, end the the execution of this program.
So, the output is
32
Secondly, Take your changed code as an example:
#include <stdio.h>
int main(){
for (printf ("3"); printf("2"); printf("1")) ;
return 0;
}
Output
321212121212121212...121212...1212...
Similarly,
1.initialization is "printf ("3")", then, print:
3
2.The test expression "printf("2")", that always true, so print:
2
3.for body loop "``", empty, then do nothing. goto the updated expression
"printf("1")"
4.the updated expression "printf("1")", then, print
1
5.then, goto the test expression "printf("2")", that is "2.The test
expression "printf("2")", that always true, so print".Because the
the body of loop is "``",empty, then always goto from the updated
expression "printf("1")" to the test expression "printf("2")",
that's why after printing "32" that function prints infinite loop
"12".And, that function never end stop printing "12" unless you
stop that function.
So, So, So the output is
32121212...121212...121212...
Thirdly, Take your recently changed code as an example:
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
Output
32
1.the program begins to run from the left ‘{’ of function main(),
that's the initialization statement of Temporary variable
"int a=1;".
該陳述句定義了一個“ int”型別臨時變數“ a”,并且
將它的值設定為“ 1”,但是什么都不列印!
2.然后,程式轉到for回圈。
3.初始化陳述句是“ printf ("3")”,然后,列印
“ 3”,和
轉到測驗運算式。
3
4. 測驗運算式" printf("2")",總是正確的,所以
列印“ 2”,然后轉到 for 回圈體運算式。
2
5.for回圈體運算式“ return 0”,運算式
" return 0" 回傳 ' 0' 到函式 main(),并結束
執行 main(),但不列印任何內容。
所以,輸出是:
32
結尾。謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364677.html
