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.
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
For example, if the problem is “What is 5/7 of 93,” then “5” is the numerator, “7” is the denominator and “93” is the whole number. Divide the whole number by the denominator. Using the same example, divide 93 / 7 = 13.3.
Floating point numbers are different from integer numbers in that they contain fractional parts. Even if the number to the right of the decimal point is 0 (or decimal comma, if your locale uses commas instead of periods), it's still a fractional part of the number. Floating point numbers can be positive or negative.
Python math function | modf() modf() function is an inbuilt function in Python that returns the fractional and integer parts of the number in a two-item tuple. Both parts have the same sign as the number. The integer part is returned as a float.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With