![](/img/trans.png)
[英]Why does using float instead of int gives me different results when all of my inputs are integers?
[英]When using int and float datatype,why the output of "%d" is showing different?
#include <stdio.h>
#include <conio.h>
int main() {
int a = 2;
float b = 4;
clrscr();
printf("%d \n", a + b);
printf("%f \n", a + b);
printf("%d \n", a * b);
printf("%f \n", a * b);
printf("%d \n", b / a);
printf("%f \n", b / a);
getch();
return 0;
}
Output:-
-1293228905
6.000000
0
8.000000
0
2.000000
似乎它只是采用int
数据类型的开始和结束范围。
对于使用%d
转换的所有printf
语句,您的代码具有未定义的行为。 原因是您传递了一个float
类型的值,其中printf
将期望传递一个int
类型的值。
为了计算表达式a+b
,编译器将int
操作数转换为float
类型并使用浮点计算计算加法。 结果的类型也是float
。 这同样适用于其他表达式。
类型int
和float
具有不同的表示形式,可以以不同的方式传递给可变参数函数,例如printf
。 如果您打算使用%d
,则必须使用强制转换将该值显式转换为int
类型:
printf("%d \n", (int)(a + b));
请注意,您还可以将%.0f
用于 output 不带小数的float
参数,但 output 会有所不同,因为printf
会将float
值舍入到最接近的 integer,而(int)(a + b)
会将float
值截断为0
如果它可以表示为int
。
最后请注意,当传递给printf
和其他可变参数函数时, float
值被隐式提升为double
精度值。 建议对所有浮点类型使用double
精度类型,除非您的目标是非常具体的应用程序,例如计算机图形或嵌入式系统。
这是修改后的版本:
#include <stdio.h>
int main() {
int a = 2;
double b = 4;
printf("a+b: %f %d %.0f\n", a + b, (int)(a + b), a + b);
printf("a*b: %f %d %.0f\n", a * b, (int)(a * b), a * b);
printf("a/b: %f %d %.0f\n", a / b, (int)(a / b), a / b);
printf("b/a: %f %d %.0f\n", b / a, (int)(b / a), b / a);
getchar();
return 0;
}
Output:
a+b: 5.000000 5 5
a*b: 6.000000 6 6
a/b: 0.666667 0 1
b/a: 1.500000 1 2
在 C 中, %d
说明符用于打印一个 int 值, %f
用于打印一个浮点数。
在这一行中printf("%d \n", a + b);
您正在尝试添加一个 integer 和一个浮点数,然后使用%d
说明符打印结果。 这显示错误的结果为 output。
在这一行中printf("%d \n", a * b);
您正在将 integer 与浮点数相乘并使用%d
说明符打印结果。 结果它也显示了错误的 output。 要在此处正确打印 output,您应该使用%f
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.