Thread: Restricted floats for scanf

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    29

    Restricted floats for scanf

    I'm trying to use a scanf to get an input from the user of 2.1 or 2.2 to activate a function call and haven't found much to solve this.

    I'm using a float type and when I watch it stores as 2.099999.... therefore the function does not run. Is there a way to suppress the stored number?

    I did try using char and strcmp but it caused more problems.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    Read up on floating point numbers. "2.1" and "2.2" cannot be represented accurately. If you want to do something only when the input is a specific real number, you need to add some tolerance to account for rounding errors. For example:
    Code:
    #include <math.h>
    
    #define F32_TOLERANCE 0.001f
    
    int equal_f32(float a, float b)
    {
        return fabsf(a - b) <= F32_TOLERANCE;
    }
    
    ...
        if (equal_f32(input, 2.1f)) {
            /* Do stuff */
        }
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Restricted pointers C99.
    By Mr.Lnx in forum C Programming
    Replies: 7
    Last Post: 07-20-2013, 07:06 PM
  2. A little help here with long floats/scanf/printf
    By cprogrammer1980 in forum C Programming
    Replies: 6
    Last Post: 03-04-2011, 02:18 PM
  3. Restricted Integer
    By kolucoms6 in forum C++ Programming
    Replies: 6
    Last Post: 03-01-2008, 08:59 PM
  4. Forum Restricted
    By XelleX90 in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-26-2006, 08:54 AM
  5. rewritten scanf for floats
    By monkey_C in forum C Programming
    Replies: 3
    Last Post: 12-09-2002, 04:21 PM

Tags for this Thread