《C程序设计语言》第二版 Exercise1-15

Exercise 1.15. Rewrite the temperature conversion program of Section 1.2 to use a function for conversion.

Let us see the Fahr-to-Celsius program in Section 1.2 first:

#include <stdio.h>

/* print Fahrenheit-Celsius table
    for fahr = 0, 20, ..., 300; floating-point version */

main() {
    float fahr, celsius;
    float lower, upper, step;

    lower = 0;
    upper = 300;
    step = 20;

    fahr = lower;
    while (fahr <= upper) {
        celsius = (5.0 / 9.0) * (fahr - 32.0);
        printf("%3.0f %6.1f\n", fahr, celsius);
        fahr = fahr + step;
    }
}

There are may ways for us to set up functions. For example: one function for table printing and the other for celsius calculation. Or a "big" function including both caculation and printing. Or just a calculation function, and remain the while/for circulation. It depends on your preference. However, I would like the final one and the function will be:

double fahrToCelsius(double fahr) {
    return (fahr - 32) * 5.0 / 9.0;
}

Then just remove the celsius calculation in the main() and replace the celsius in printf() by the function calling. We can get the new program with function utilization.

#include <stdio.h>

#define UPPER 300
#define LOWER 0
#define STEP 20

double fahrToCelsius(double fahr);
int main(void) {
    double fahr;
    for (fahr = LOWER; fahr <= UPPER; fahr += STEP)
        printf("%3.0f\t%6.1f\n", fahr, fahrToCelsius(fahr));
    return 0;
}

double fahrToCelsius(double fahr) {
    return (fahr - 32) * 5.0 / 9.0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值