为什么整数除法的结果为零而不是小数?
自学 C 语言,发现当我做一个临时转换方程时,除非我将分数更改为小数,否则它不会起作用。即,
tempC=(.555*(tempF-32))
可以工作,但 tempC=((5/9)*(tempF-32))
不起作用。
为什么?
根据“C Primer Plus”一书,它应该可以工作,因为我对 tempC 和 tempF 使用浮点数。
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. ie,
tempC=(.555*(tempF-32))
will work but tempC=((5/9)*(tempF-32))
won't work.
Why?
According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看起来您在第二种情况下进行了整数除法:
5 / 9
将被截断为零。要解决这个问题,您需要将其中之一设为浮点类型:
It looks like you have integer division in the second case:
The
5 / 9
will get truncated to zero.To fix that, you need to make one of them a floating-point type:
当你计算 5/9 时,5 和 9 都是整数,并且会发生整数除法。整数除法的结果是一个整数,它是两个操作数的商。因此,5/9 的商为 0,并且由于乘以 0,tempC 结果为 0。为了不进行整数除法,两个操作数中至少有一个必须是浮点型。
例如,如果您使用 5.0/9 或 5/9.0 或 5.0/9.0,它将按预期工作。
When you do 5/9, 5 and 9 are both integers and integer division happens. 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
.E.g. if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.
5/9 是整数除法而不是浮点除法。这就是为什么你会得到错误的结果。
设置 5 或 9 个浮点变量,您将得到正确的答案。
喜欢 5.0/9 或 5/9.0
5/9 is an integer division not a floating point division. That's why you are getting wrong result.
Make 5 or 9 floating point variable and you will get correct answer.
Like 5.0/9 OR 5/9.0
5/9
是一个整数表达式,因此它会被截断为 0。您的编译器应该对此发出警告,否则您应该考虑启用警告。5/9
is an integer expression, as such it gets truncated to 0. your compiler should warn you about this, else you should look into enabling warnings.如果将 5/9 放在括号中,则将首先计算它,并且由于它们是两个整数,因此将通过整数除法完成,结果将为 0,然后再计算表达式的其余部分。
您可以重新排列表达式,以便首先转换为浮点数:
tempC=((5/9)*(tempF-32));
→tempC=(5*(tempF-32) ))/9;
或者当然,正如其他人所说,使用浮点常量。
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.
You can rearrange your expression so that the conversion to float occurs first:
tempC=((5/9)*(tempF-32));
→tempC=(5*(tempF-32))/9;
or of course, as the others say, use floating point constants.