1

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);

}
Daniel
  • 43
  • 3
  • By using `fabs()` and an EPSILON (tolerance) value. `if(fabs(FtoC(41.9) - 5.5) < 0.1)` but typically a much samller EPSILON can be used. – Weather Vane Sep 13 '22 at 17:46
  • Does this answer your question? [Compare two float variables in C++](https://stackoverflow.com/questions/56039679/compare-two-float-variables-in-c) – Iłya Bursov Sep 13 '22 at 17:49
  • This [What is the most effective way for float and double comparison?](https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison) is popular but also C++. – Weather Vane Sep 13 '22 at 17:51
  • 1
    Don’t. This is not even a floating-point problem. Even if we used perfect real-number arithmetic, a temperature is essentially never exactly 5.5 ºC anyway. There are always fluctuations, both in the actual temperature and in measurement. And even if it was exactly 5.5 ºC when you measured it a moment ago, it has changed slightly. Why should a program ever depend on some temperature being exactly 5.5 ºC? Normally, something is triggered when a temperature goes above or below a threshold, not when it is exactly at a threshold. So testing for equality is probably not the right thing to be doing. – Eric Postpischil Sep 13 '22 at 17:55
  • @EricPostpischil It is only an exercise. The programm has no use in the real world. I just want to know how to limit the amout of decimal places. And if possible to compare two float values – Daniel Sep 13 '22 at 18:01

1 Answers1

2

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);
}
Semyon
  • 111
  • 4
  • It is also worth clarifying that this code will only work correctly If you're using C99 or better, rather than ANSI C/C89/C90 You can read more [in this question](https://stackoverflow.com/questions/497018/is-there-a-function-to-round-a-float-in-c-or-do-i-need-to-write-my-own). – Semyon Sep 13 '22 at 18:14
  • Comparing a `float` to a `double` constant is brittle code. OK this time as `5.5 == 5.5f`, yet if the target was `C == 5.6`, this code would fail. – chux - Reinstate Monica Sep 13 '22 at 21:27