利用c語言scanf返回值來控制非數字值時循環結束

利用c語言scanf返回值來控制非數字值時循環結束

最近在學C語言,參考書籍是Stephen Prata《C Primer Plus》。第五章最後一個編程練習很有意思,題目如下:

編寫一個程序,該程序要求用戶輸入一個華氏溫度.程序以double類型讀入溫度值,並將它作爲一個參數傳遞給用戶提供的函數Temperatures().該函數將計算相應的攝氏溫度和絕對溫度,並將以小數點右邊的兩位數字的精度顯示這三種溫度.它應該用每個值所代表的溫度刻度來標識這3個值.
下面是將華氏溫度轉換成攝氏溫度的方程:
Celsius=1.8*Fahrenheit+32.0
通常用在科學上的絕對溫度刻度是0代表絕對零,是可能溫度的下界.
下面是攝氏溫度轉換成絕對溫度的方程:
Kelvin=Celsius+273.16
Temperatures()函數使用const來創建代表該轉換裏的3個常量符號.main()函數將使用一個循環來允許用戶重複地輸入溫度,當用戶q或其他非數字值時,循環結束.

題目很簡單,最後一個要求“當用戶q或其他非數字值時,循環結束”卻有意思。我們可以用scanf()函數的返回值來實現該功能。

scanf()函數返回成功賦值的數據項數,讀到文件末尾出錯時則返回EOF。
比如:

scanf("%d %d",&a,&b);

(1) 如果a和b都被成功讀入,那麼scanf的返回值就是2
(2) 如果只有a被成功讀入,返回值爲1
(3) 如果a和b都未被成功讀入,返回值爲0
(4) 如果遇到錯誤或遇到end of file,返回值爲EOF。
這裏,返回值爲int型.

這樣,我們就可以利用scanf()返回值的特點,在本題中,檢驗輸入的double類型的溫度值,如果返回值不是1,就終止循環。

    int judge;double d_fah;
    judge = scanf("%lf", &d_fah);
    while (judge == 1)
    {...}

這裏也附上完整代碼,歡迎各位看官批評指正。

// temperature.c print the temperatures in Fahrenheit, Celsius and Kelvin
// Dec. 04, 2015
#include<stdio.h>
void Temperatures(double);

int main(void)
{
    double d_fah;
    int judge;
    printf("This program shows input temperature value in different foramt.\n");
    printf("Enter a temperature value :(enter q/Q and non-numerical values to quit): ");
    judge = scanf("%lf", &d_fah);
    while (judge == 1)
    {
        Temperatures(d_fah);
        //printf("%.2f/n", d_fah);//testing
        printf("Enter a temperature value :(enter q/Q and non-numerical values to quit): ");
        judge = scanf("%lf", &d_fah);
    }
    printf("\nBye~~~\n");
}

void Temperatures(double d_fah)/*print the temperatures in Fahrenheit,
                               Celsius and Kelvin*/
{
    const double Fah_TO_Cel1 = 1.8;
    const double Fah_TO_Cel2 = 32.0;
    const double Cel_TO_Kel = 273.16;
    double d_cel, d_kel;
    d_cel = Fah_TO_Cel1 *d_fah + 32.0;
    d_kel = d_cel + Cel_TO_Kel;
    printf("Your input temperature value can be printed in three different format.\n");
    printf("Fahrenheit: %.2lfF.   Celsius: %.2lfC.   Kelvin: %.2lfK.\n\n", d_fah, d_cel, d_kel);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章