任何人都可以解释为什么当我将它除以整数时b会在这里被舍入,尽管它是一个浮点数?
#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
}
Run Code Online (Sandbox Code Playgroud)
Suk*_*lra 31
这是因为隐式转换.变量b, c, d
属于float
类型.但是/
运算符看到它必须除以两个整数,因此在结果中返回一个整数,该整数float
通过添加小数点隐式转换为a .如果你想要浮点除法,请尝试将两个操作数设置为/
浮点数.如下.
#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;
}
Run Code Online (Sandbox Code Playgroud)
Cac*_*nta 12
使用类型的铸件:
int main() {
int a;
float b, c, d;
a = 750;
b = a / (float)350;
c = 750;
d = c / (float)350;
printf("%.2f %.2f", b, d);
// output: 2.14 2.14
}
Run Code Online (Sandbox Code Playgroud)
这是解决这个问题的另一种方法:
int main() {
int a;
float b, c, d;
a = 750;
b = a / 350.0; //if you use 'a / 350' here,
//then it is a division of integers,
//so the result will be an integer
c = 750;
d = c / 350;
printf("%.2f %.2f", b, d);
// output: 2.14 2.14
}
Run Code Online (Sandbox Code Playgroud)
但是,在这两种情况下,您都告诉编译器350是浮点数,而不是整数.因此,除法的结果将是浮点数,而不是整数.