为什么将两个整数相除不会得到浮点数? [英] Why dividing two integers doesn't get a float?
本文介绍了为什么将两个整数相除不会得到浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能解释为什么当我把它除以一个整数时 b 会被四舍五入,尽管它是一个浮点数?
Can anyone explain why b gets rounded off here when I divide it by an integer although it's a float?
#include <stdio.h>
void main() {
int a;
float b, c, d;
a = 750;
b = a / 350;
c = 750;
d = c / 350;
printf("%.2f %.2f", b, d);
// output: 2.00 2.14
}
推荐答案
这是因为隐式转换.变量 b, c, d
是 float
类型.但是 /
运算符看到它必须除以的两个整数,因此在结果中返回一个整数,该整数通过添加小数点隐式转换为 float
.如果您想要浮点数除法,请尝试将两个操作数设置为 /
浮点数.喜欢如下.
This is because of implicit conversion. The variables b, c, d
are of float
type. But the /
operator sees two integers it has to divide and hence returns an integer in the result which gets implicitly converted to a float
by the addition of a decimal point. If you want float divisions, try making the two operands to the /
floats. Like follows.
#include <stdio.h>
int main() {
int a;
float b, c, d;
a = 750;
b = a / 350.0f;
c = 750;
d = c / 350;
printf("%.2f %.2f", b, d);
// output: 2.14 2.14
return 0;
}
这篇关于为什么将两个整数相除不会得到浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文