[英]How can I compare float values
I wrote this little code to get from Fahrenheit to Celcius.我写了这个小代码来从华氏温度到摄氏度。 I know that when I type "float a = 41.9" the value is 41.90000045 or something.我知道当我输入“float a = 41.9”时,值是 41.90000045 或其他东西。 How can I limit the decimal places to only 1 so that my "if-statement" will become true?如何将小数位限制为 1,以便我的“if 语句”变为真?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
float FtoC(float a);
int main()
{
if (FtoC(41.9) == 5.5){
printf("%f\n", FtoC(41.9));
}
return 0;
}
float FtoC(float a){
float x = (a - 32.0) / 9.0 * 5.0;
return(x);
}
You can include math.h
lib and use roundf
function.您可以包含math.h
库并使用roundf
function。
#include <math.h>
float C = roundf(FtoC(41.9)*10.0f)/10.0f
if ( C == 5.5) {
printf("%f\n", C);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.