2014-07-22 30 views
-1

嗨匹配輸出下面我有一個C函數:輸入不使用C

int method2(){ 
    int userInput; 
    printf("Please enter your age: "); 
    scanf("%d", &userInput); 

    fpurge(stdin); 

    printf("You are %d years old. \n", &userInput); 

    int retval = 0; 
    return retval; 
} 

該函數將年齡,並返回一個強大的句子相同的值。

所以,當我運行它作爲類型12年齡。我得到

You are 1606416204 years old. 
+1

'printf'中的'&userInput' - >'userInput'閱讀一本書以理解爲什麼'printf'和'scanf'在這裏有所不同。 –

+0

'userInput'的計算結果是userInput的地址,而userInput的計算結果是它的值。 – Rohan

回答

2

正在打印的變量userInput而不是其價值的地址,使用printf如下

printf("You are %d years old. \n", userInput); 

這將打印出現在變量userInput值。

1
printf("You are %d years old. \n", &userInput); 
            ^
            |..//remove &  

您在這裏&userInput'.印刷地址應該是userInput

1

你感到困惑的printfscanf

變化的用法:

printf("You are %d years old. \n", &userInput); 

到:

printf("You are %d years old. \n", userInput); 
1

你怎麼會列入userInput的&的printf的? &評估地址。我們希望userInput的代替,所以將其更改爲:

printf("You are %d years old. \n", userInput); 

,讓我知道會發生什麼。

1

您正在打印地址而不是值。將代碼更改爲此 -

printf("You are %d years old. \n", userInput); 

它肯定會有效。