繁体   English   中英

如何比较浮点值

[英]How can I compare float values

我写了这个小代码来从华氏温度到摄氏度。 我知道当我输入“float a = 41.9”时,值是 41.90000045 或其他东西。 如何将小数位限制为 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);

}

您可以包含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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM