Devyn Hedin
Devyn Hedin

Reputation: 37

C - Calculating and printing int as float

I'm writing a switch statement and trying to print f as a float. In this context a is 40 and b is 400, so I need to print out 0.1

My question is, since f is an int, how can I go about this? I've already tried using %f instead of %d and I've also cast a as a float. But every time it just prints 0.00000000

case '/': f = a / b; printf("f = %d\n", f);

Just to clarify all three values are ints.

Upvotes: 0

Views: 6194

Answers (4)

Govind Parmar
Govind Parmar

Reputation: 21542

The %f format specifier will not magically convert the result of integer division to a floating point number for you, nor will it treat an int as a float or double. You need to declare f as a float yourself, and ensure that the operation a / b is not treated as integer division:

float f;
...

case '/': 
    f = (float)a / (float)b;
    printf("f = %f\n", f);

Upvotes: 0

Raindrop7
Raindrop7

Reputation: 3911

you cannot store a float value in an integer one because the decimal part will be discarded, converted implicitly to an integer so you have to declare f as float or double or float:

float f;
int a(40), b(400);
f = (float)a / (float)b;
printf("%g", f);

Upvotes: 0

Mendes
Mendes

Reputation: 18451

You should cast the result of the division to float before storing to your f variable:

case '/': f = (float) a / b; printf("f = %.2f\n", f);

You can also use %n.nf to print the number of decimals you want to. In the above example 2 decimals.

Another example code:

float f;
int a = 5;
int b = 3;

f = (float) a/b;

printf ("%2.2f\n", f);

Upvotes: 1

dbush
dbush

Reputation: 223882

If you want f to store a float value, you need to declare it as a float. You also need to cast either a or b to float for the result of the division to be a float.

Then you can use the %f format specifier to print it.

float f;
...
case '/': f = (float)a / b; printf("f = %f\n", f);

Upvotes: 4

Related Questions