码迷,mamicode.com
首页 > 其他好文 > 详细

Why celsius = 5 * (fahr - 32) / 9 ?

时间:2015-03-16 16:31:34      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:c   c语言中的整数除法   integer division   

Go to my personal blog

There is a program to print Fahrenheit-Celsius table as below.

#include <stdio.h>

/* print Fahrenheit-Celsius table 
    for fahr = 0, 20, ..., 300 */
int main()
{
	int fahr, celsius;
	int lower, upper, step;

	lower = 0;    /* lower limit of temperature table */
	upper = 300;  /* upper limit */
	step = 20;    /* step size */

	fahr = lower;
	while (fahr <= upper)  {
		celsius = 5 * (fahr - 32) / 9;
		printf("%d\t%d\n", fahr, celsius);
		fahr = fahr + step;
	}
}

技术分享


The right part of the figure is the output of this program. The Celsius temperature is computed and assigned to the variable celsius by the statement

celsius = 5 * (fahr - 32) / 9;

The reason for multiplying by 5 and then dividing by 9 instead of just multiplying by 5/9 is that in C, as in many other languages, integer division truncates: any fractional part is discarded. Since 5 and 9 are integers, 5/9 would be truncated to zero and so all the Celsius temperatures would be reported as zero.

Reference

Why celsius = 5 * (fahr - 32) / 9 ?

标签:c   c语言中的整数除法   integer division   

原文地址:http://blog.csdn.net/abnerwang2014/article/details/44306535

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!