標籤:class blog get 類 表 代碼
第五章的最後一個練習題,5-8.
要求:
/*輸入一個華氏溫度。以double類型讀入溫度值,並將它作為一個參數傳遞給使用者提供的函數Temperatures()。該函數將計算對應的攝氏溫度和絕對溫度,並以小數點右邊有兩位元字的精度顯示這三種溫度。它應該用每個值所代表的溫度刻度來標識這三個值。Celsius = 1.8 * Fahrenheit + 32.0Kelvin = Celsius + 273.16*/
最開始,我寫了如下的代碼:
先用gets(),擷取輸入字串,再比較第一個字元是否是數字來判斷輸入是否合法,再用sscanf()函數讀取輸入字串中的數字。
#include <stdio.h>void Temperatures(double Fahrenheit);int main(void){double tmp;char str[20];printf("Enter a temperature in Fahrenheit:\n");gets(str);while (str[0] >= ‘0‘ && str[0] <= ‘9‘){sscanf(str,"%lf", &tmp);Temperatures(tmp);printf("Enter a temperature in Fahrenheit:\n");gets(str);}return 0;}void Temperatures(double Fahrenheit){float Celsius, Kelvin;Celsius = 1.8 * Fahrenheit + 32.0;Kelvin = Celsius + 273.16;printf("%.2f %.2f %.2f", Fahrenheit, Celsius, Kelvin);}
後來發現,如過利用scanf()的傳回值作為判斷,可以簡化代碼。
scanf()函數的傳回值是成功讀入的項目的個數,假如沒有讀取任何項目,則傳回值為0。
簡化後的代碼:
#include <stdio.h>void Temperatures(double Fahrenheit);int main(void){double tmp;printf("Enter a temperature in Fahrenheit:\n");while (scanf("%lf", &tmp)){Temperatures(tmp);printf("Enter a temperature in Fahrenheit:\n");}return 0;}void Temperatures(double Fahrenheit){float Celsius, Kelvin;Celsius = 1.8 * Fahrenheit + 32.0;Kelvin = Celsius + 273.16;printf("%.2f %.2f %.2f", Fahrenheit, Celsius, Kelvin);}