0

The following is my code :

float f;
int counter = 0;
float amount;
do
{
    printf("O Hai! How much money do I owe?\n ");
    amount = get_float();
} while(amount <= 0);
 /* rounds off the input value*100 to a floating point number and casts into 
an integer */
f = (int) roundf(amount*100); 

Now, the issue is that even if I cast the rounded off value to an integer how can a floating point variable store the value of an integer ?

0

If you are asking why it's mathematically logical to do that, that's because the set of integer numbers is a subset of the set of real numbers in mathematics. If you mean how it's possible in code read further.

In C, and other languages derived by C, you can assign a value to variable that has greater precision without the need of any casting. So you can assign an int value to a long variable or even a long long (both long and long long are integer representations that just use more bits. An int has at least 16 bits, a long has at least 32 bits and a long long has at least 64 bits). This procedure is called Integer Promotion.

Now in case you don't explicitly cast a type to another, if the type of the variable you assign to has a different type of the value, and if the type of the variable has greater precision, then an implicit cast is happening, and the value is stored in the greatest precision.

For example the following is valid and compiles:

int i = 5;
float f = i;
printf("%f\n", f);

and prints:

5.000000

The same is happening when you have operations between two different data types, the one with the least precision gets implicitly cast to the type with the greatest precision, like so:

int i = 5;
float f = 5.0;
printf("%f\n", f * i);

and prints:

25.000000

So the int was first cast to a float, and then the product of the two floats was computed.

What you want to do instead, is cast a float to an int, and store it inside an int variable. You can do it like so:

float f = 5.0;
int i = (int) f;
printf("%d\n", i);

which will print:

5

More precisly you want to do this:

#include <stdio.h>
#include <math.h>

int main(void) {
    float f = 5.5;
    int i = (int) round(f);
    printf("%d\n", i);

    return 0;
}

which prints:

6

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .