簡體   English   中英

交流編程問題

[英]a c programming question

所有。 我不確定在這里問這樣一個“簡單”的問題是否合適,但實際上對我來說很困難:[,這是一個問題和一些C代碼:

main()
{
    int c, i;
    for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
        printf("%d", i);
    if (c == '\n')
        printf("%d", i);
}

執行此程序后,當我輸入“ abc \\ n”時,程序將返回:

0
1
2
3

我想知道為什么結果不是

0
1
2

因為當c =='\\ n'時,沒有語句使i遞增1。這就是我的想法,我一定錯了,您能告訴我哪里錯了嗎? 謝謝!

主要問題在於索引變量i的預遞增。 代替預增量,在for循環中使用后增量,即i ++。其背后的原因是預增量。 當循環中的條件停止時,使用預增量時,i中存儲的值已經為4。

main()
{
    int c, i;
    for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)
        printf("%d", i);
    if (c == '\n')
        printf("%d", i);
}

所述++i獲取之后執行c == '\\n'的情況下。

也許這段代碼將有助於闡明?

int i;
for (i = 0; i <= 3; ++i)
    printf("%d\n", i);

在循環結束時,由於最終的增量,我將為4。

for循環中的操作順序為:

i = 0
(c = getchar()) != EOF && c != '\n' // c is set to 'a'
printf("%d", i)    // displays 0

++i   // i == 1
(c = getchar()) != EOF && c != '\n' // c is set to 'b'
printf("%d", i)    // displays 1

++i   // i == 2
(c = getchar()) != EOF && c != '\n' // c is set to 'c'
printf("%d", i)    // displays 2

++i   // i == 3
(c = getchar()) != EOF && c != '\n' // c is set to '\n'
// the loop exits

因此,在for循環之后的printf()打印i最新值, i 3。

暫無
暫無

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

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