2013-07-24 93 views
6

我是C的初學者。請不要介意我的問題是否跛腳。在我編寫的這個程序中,當我第一次使用'for'循環時,我期望只有3個值被存儲在一個數組中,但它存儲了4個值,並且在下一個'for'循環中如期望的那樣顯示了3個值。 我的問題是爲什麼在第一'for'循環它需要4個值而不是3?從輸入數組中存儲數據

#include<stdio.h> 
void main() 
{ 
    int marks[3]; 
    int i; 

    for(i=0;i<3;i++) 
    { 
     printf("Enter a no\n"); 
     scanf("%d\n",(marks+i)); 
    } 
    for(i=0;i<3;i++) 
    { 
     printf("%d\n",*(marks+i)); 
    } 
} 
+2

'無效main'是不合法的。使用'int main'。 – chris

+4

在scanf –

回答

11

scanf\n是問題

#include<stdio.h> 
int main() 
{ 
    int marks[3]; 
    int i; 

    for(i=0;i<3;i++) 
    { 
     printf("Enter a no\n"); 
     scanf("%d",(marks+i)); 
    } 

    printf("\nEntered values:\n"); 
    for(i=0;i<3;i++) 
    { 
     printf("%d\n",*(marks+i)); 
    } 

    return 0; 
} 

原因是:

我期望僅3值被存儲在數組中,但它存儲4個值 和在下一'爲'循環如預期顯示3個值。我的問題是爲什麼 在1st'for'循環中需要4個值而不是3個?

第一:沒有,只存儲3數量,但在陣列marks[]4數字。

第二個:有趣的理解循環運行只有三次i = 0i < 3。 for循環根據條件運行。更有趣的代碼是停留在scanf()如下所述:

你的困惑就是爲什麼你必須輸入四位數字組成,它不會因爲你循環運行4倍,但它的,因爲當你輸入一個非空格字符scanf()函數只返回(並在後輸入按下輸入一個非空格字符的數字符號)。

爲了理解這個行爲讀手冊:int scanf(const char *format, ...);

的空白字符的序列(空格,製表,換行,等;見 isspace(3))。該指令與輸入中的任意數量的空白空間 (包括無)匹配。

因爲第一個for循環在,在scanf()已包含在格式字符串\n,所以只有scanf()的回報,如果按一個數字進入(或非空間)。

scanf("%d\n",(marks+i)); 
     ^
      | 
      new line char 

會發生什麼情況?

假設輸入程序是:

23  <--- because of %d 23 stored in marks[0] as i = 0 
<enter> <--- scanf consumes \n, still in first loop 
543  <--- scanf returns, and leave 542 unread, 
           then in next iteration 543 read by scanf in next iteration 
<enter> 
193 
<enter> <--- scanf consumes \n, still in 3rd loop 
<enter> <--- scanf consumes \n, still in 3rd loop 
123  <--- remain unread in input stream 
+0

thanx DX中刪除'\ n',但是當我在scanf中的%d之後使用\ n後,當i的值爲0時首次需要2個值,但當i的值變爲1和2時,它只需要1個,爲什麼有時候是這樣的? – ranaarjun

+1

請經過這http://answers.yahoo.com/question/index?qid=20110801122000AA07FO8希望這給你的確切原因 –

+1

@GrijeshChauhan肯定會有所幫助:)請做 –

0

刪除\ni可以在if語句來創建爲for (int i = 0; i < 3; i++) {}