简体   繁体   中英

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. How can I limit the decimal places to only 1 so that my "if-statement" will become true?

#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.

#include <math.h>

float C = roundf(FtoC(41.9)*10.0f)/10.0f
if ( C == 5.5) {
    printf("%f\n", C);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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