0

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.

Devyn Hedin
  • 37
  • 3
  • 7
  • 1
    why storing a float value in an int? it will be converted to int – Raindrop7 Jan 25 '17 at 22:15
  • 1
    `a`,`b` are `int` ? – Mohsen_Fatemi Jan 25 '17 at 22:15
  • 2
    Possible duplicate of [What is the behavior of integer division in C?](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c) – OldProgrammer Jan 25 '17 at 22:16
  • Possible duplicate of [Why does this output of the same expression from printf differ from cout?](http://stackoverflow.com/questions/19102778/why-does-this-output-of-the-same-expression-from-printf-differ-from-cout) – Govind Parmar Jan 25 '17 at 22:17

4 Answers4

4

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);
dbush
  • 205,898
  • 23
  • 218
  • 273
1

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);
Mendes
  • 17,489
  • 35
  • 150
  • 263
0

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);
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
0

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);
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85