2016-07-24 17 views
0

我在下面的循環中得到一個不尋常的輸出。當它在我的編譯器中運行時,輸出是233445。爲什麼我會在下面的循環中獲得這個輸出? 7將是這個循環的唯一合理輸出,爲什麼當printf語句位於循環內部時,我沒有得到7C中的循環輸出出現異常

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    int i; 
    int j; 

    for (i = 1; i < 4; i++) 
     for (j = 1; j < 3; j++) 
      printf("%d", i + j); 
} 
+2

「爲什麼當'printf'語句在循環中時我不會得到7?」因爲'i <4'和'j <3',所以'i + j <4 + 3'並且它意味着'i + j <7',所以'i + j'在循環內不會是'7' 。 – MikeCAT

+0

i和j在循環之前的值爲1 –

回答

0

是的,printf語句在循環中。要獲得7,您可以在循環後放置{}以使其脫離循環。

1
#include <stdio.h> 
#include <stdlib.h> 

int main() { 
int i ; 
int j ; 
for(i=1; i<4;i++) 
    for(j=1;j<3;j++) 
     printf("%d",i+j);  
} 

該代碼從i = 1開始執行三次外循環。它進入內部循環並從j = 1開始運行兩次。然後它爲第一個循環打印2,3,爲第二個循環打印3,4,爲第三個循環打印4,5

爲了清楚起見,我添加了逗號,並顯示內循環確實運行了兩次,但實際輸出爲233445,因爲您沒有添加任何分隔符或換行符。

如果您爲使用循環輸出要7,嘗試:

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    int i ; 
    int j ; 
    for(i=4; i<5;i++) { // this brace means it contains the inner loop. 
     for(j=3;j<4;j++) { // this inner brace means it contains control of the statement. 
      printf("%d",i+j); // and always remember to indent for your readers 
     } // close the inner brace! 
    } // close the outer brace! 
} // close main brace 

或者,你可以嘗試增加使用循環的數量,然後打印出來的循環外,如其他人所說:

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    int i ; 
    int j ; 
    for(i=1; i<4;i++) { // this brace means it contains the inner loop. 
     for(j=1;j<3;j++) { // this inner brace means it contains control of the statement. 
     } // close the inner brace! 
    } // close the outer brace! 
    printf("%d",i+j); // 7 
} // close main brace 
+0

也許爲兩個循環添加大括號將使OP – babon

+0

@babon更容易。我已經附加了這個。 –

6

爲什麼我在下面的循環中得到這個輸出?

製作一個圖表,你會看到。

i | j | i+j 
--+---+---------------------------- 
1 | 1 | 2 
1 | 2 | 3 
1 | 3 | (get out of the inner loop) 
2 | 1 | 3 
2 | 2 | 4 
2 | 3 | (get out of the inner loop) 
3 | 1 | 4 
3 | 2 | 5 
3 | 3 | (get out of the inner loop) 
4 | - | (get out of the outer loop) 

爲什麼我沒有拿到7printf語句是在循環內?

由於i<4j<3,所以i+j < 4+3它意味着i+j<7,所以i+j不會7在循環內。