Determining if a float has a fractional part?

TheMegalomaniac picture TheMegalomaniac · Dec 18, 2011 · Viewed 16k times · Source

Here is the problem: The game Totals can be played by any number of people. It starts with a total of 100 and each player in turn makes an integer displacement between -20 and 20 to that total. The winner is the player whose adjustment makes the total equal to 5. Using only the three variables given: total adjustment counter Here is what I have so far:

#include <stdio.h>
int main (void)
{
    int counter=0;
    float adj;
    int ttl=100;

    printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");

    while (ttl!=5)
    {
        printf("YOUR ADJUSTMENT?");
        scanf("%f",&adj);
        counter++;
        if (adj<=20 && adj>=-20)
        {
        ttl=ttl+adj;
        printf("The total is %d\n",ttl);
        }
        else
        {
        printf ("I'm sorry. Do you not know the rules?\n");
        }
    }
    printf("The game is won in %d steps!",counter);

}

What I need: When a decimal number is entered it goes to the else. How do I determine if a float has a fractional part.

Answer

Filip Ros&#233;en - refp picture Filip Roséen - refp · Dec 18, 2011

You can cast the float to an int and then compare it to your original variable. If they are the same there was no fractional part.

By using this method, there is no need for a temporary variable or a function call.

  float adj;

  ....     

  if (adj == (int)adj)
    printf ("no fractional!\n");
  else
    printf ("fractional!\n");
  

Explanation

Since an int cannot handle fractions the value of your float will be truncated into an int (as an example (float)14.3 will be truncated into (int)14).

When comparing 14 to 14.3 it's obvious that they are not the same value, and therefore "fractional!" will be printed.