利用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);
}
  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值