简体   繁体   English

为什么除法的结果是零而不是小数?

[英]Why does division result in zero instead of a decimal?

Teaching myself C and finding that when I do an equation for a temp conversion it won't work unless I change the fraction to a decimal.自学 C 并发现当我为临时转换做一个方程式时,除非我将分数更改为小数,否则它将不起作用。 ie, IE,

tempC=(.555*(tempF-32)) will work but tempC=((5/9)*(tempF-32)) won't work. tempC=(.555*(tempF-32))将起作用,但tempC=((5/9)*(tempF-32))将不起作用。

Why?为什么?
According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.根据“C Primer Plus”一书,它应该可以工作,因为我对 tempC 和 tempF 都使用了浮点数。

It looks like you have integer division in the second case:在第二种情况下,您似乎有整数除法:

tempC=((5/9)*(tempF-32))

The 5 / 9 will get truncated to zero. 5 / 9将被截断为零。

To fix that, you need to make one of them a floating-point type:要解决这个问题,您需要将其中一个设为浮点类型:

tempC=((5./9.)*(tempF-32))

When you do 5/9, 5 and 9 are both integers and integer division happens.当你做 5/9 时,5 和 9 都是整数并且会发生整数除法 The result of integer division is an integer and it is the quotient of the two operands.整数除法的结果是一个整数,它是两个操作数的商。 So, the quotient in case of 5/9 is 0 and since you multiply by 0, tempC comes out to be 0. In order to not have integer division, atleast one of the two operands must be float .因此,在 5/9 的情况下的商为 0,并且由于您乘以 0,因此 tempC 为 0。为了不进行整数除法,两个操作数中的至少一个必须是float

Eg if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.例如,如果您使用 5.0/9 或 5/9.0 或 5.0/9.0,它将按预期工作。

5\/9 is an integer division not a floating point division. 5\/9 是整数除法而不是浮点除法。 That's why you are getting wrong result.这就是为什么你得到错误的结果。

Make 5 or 9 floating point variable and you will get correct answer.做 5 或 9 个浮点变量,你会得到正确的答案。

Like 5.0\/9 OR 5\/9.0喜欢 5.0\/9 或 5\/9.0

"

5/9是一个整数表达式,因此它会被截断为 0。你的编译器应该警告你,否则你应该考虑启用警告。

If you put 5/9 in parenthesis, this will be calculated first, and since those are two integers, it will be done by integer division and the result will be 0, before the rest of the expression is evaluated.如果你把 5/9 放在括号中,这将首先计算,因为它们是两个整数,它将通过整数除法完成,结果将为 0,然后再计算表达式的其余部分。

You can rearrange your expression so that the conversion to float occurs first:您可以重新排列表达式,以便首先转换为浮点数:

tempC=((5/9)*(tempF-32)); tempC=(5*(tempF-32))/9; tempC=(5*(tempF-32))/9;

or of course, as the others say, use floating point constants.或者当然,正如其他人所说,使用浮点常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM