C Primer Plus中的一個練習題

來源:互聯網
上載者:User

標籤: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);}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.