[英]Why is printf working but scanf isn't?
好的,所以我必須創建一個天氣程序,當我嘗試運行代碼時,沒有任何錯誤,但是它只會打印“輸入起始溫度”和“輸入終止溫度”。 但是,它不會讓我輸入數據。 我有什么需要改變的嗎? 我知道我還沒有完成代碼,但是我只想在繼續其余代碼之前先測試一下輸入。 謝謝您的幫助!
#include <stdio.h>
int main(int argc, char **argv)
{
float celcius, fahrenheit, kelvin, ending, interval;
int c, f, k, temp;
printf("which temperature is being input? (C,F,K) ");
scanf("%d", &temp);
if (temp == c)
{
printf("enter a starting temperature");
scanf("%f", &celcius);
printf("enter an ending temperature");
scanf("%f", &ending);
fahrenheit = celcius * 9 / 5 + 32;
kelvin = celcius + 273.15;
}
if (temp == f)
{
printf("enter a starting temperature");
scanf("%f", &fahrenheit);
celcius = fahrenheit - 32 * 5 / 9;
kelvin = fahrenheit - 32 * 5 / 9 + 273.15;
printf("enter an ending temperature");
scanf("%f", &ending);
if (temp == k)
{
}
printf("enter a starting temperature");
scanf("%f", &kelvin);
fahrenheit = kelvin - 273 * 1.8 + 32;
celcius = kelvin - 273.15;
printf("enter an ending temperature");
scanf("%f", &ending);
}
}
這個:
if (temp == c)
正在將temp
的新讀取值與未初始化變量c
的未定義值進行比較。 這是未定義的行為。
你可能是說
if (temp == 'c')
與角色進行比較,但是您還需要:
char temp;
if (scanf("%c", &temp) == 1)
{
if (temp == 'c')
{
/* more code here */
}
}
請注意,檢查scanf()
的返回值有助於使程序更健壯,並避免進一步使用未初始化的值(如果scanf()
無法讀取某些內容,則不應讀取目標變量,因為它不會被寫入至)。
if (temp == c)
您正在將temp與未初始化的c值進行比較
一樣
if (temp == f)
然后一切都會正常運行,使其更加用戶友好,在printf的內容中添加一個'\\ n'
像這樣,
printf("enter a starting temperature \n");
這里:
printf("which temperature is being input? (C,F,K) ");
scanf("%d", &temp);
您要求輸入一個字符,但隨后嘗試掃描int
。 這將拋出所有其余的scanf()
調用。
您的變量temp聲明為整數。 確實,scanf()想要讀取一個整數(%d),但是得到一個char。 因此,您將temp讀為char。 此外,您可以使用
9.0/5.0
代替
9/5
此外,使用switch語句將提高可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.