PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How can I compare float values

 October 24, 2022     c, compare, decimal, if-statement     No comments   

Issue

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

}

Solution

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


Answered By - Semyon
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing