0

I had a problem trying to print a fraction in C. How I can print the fraction as the number I defined below. Here is my code:

#include<stdio.h>
int main()
{
    printf("%.4f\n", 153/400);
    return 0;
}

Any help will appreciated.

unDeadHerbs
  • 1,306
  • 1
  • 11
  • 19
Schrodinger
  • 39
  • 1
  • 9
  • 2
    Write 400.0 because it is integer division now which can only have integer result. This way it will be floating point division. – Eraklon Mar 11 '20 at 08:52
  • @Eraklon Turn that into an answer please. – Yunnosch Mar 11 '20 at 09:11
  • 1
    [In C, my output of a function is always 0.000000. Is it because the two inputs are int?](https://stackoverflow.com/q/32932941/995714), [Why does division result in zero instead of a decimal?](https://stackoverflow.com/q/8906722/995714), [calculation in C program always results in 0 whenever using division](https://stackoverflow.com/q/7720078/995714) – phuclv Mar 11 '20 at 11:04

1 Answers1

3

You doing integer division now which will only result in integer. You have to perform floating point division. You can easily achieve this by writing 400.0 instead of 400 or casting one of the operand (or both if you will) to float like 153/(float)400.

Edit: As @Erwan Daniel rightly noted you have to use 400.0f to have a float literal, since on default it will be double.

unDeadHerbs
  • 1,306
  • 1
  • 11
  • 19
Eraklon
  • 4,206
  • 2
  • 13
  • 29
  • 400.0 will make a double. As C keep the most precise type, all the calculation will be made in double. The right way to write it is 400.0f of 400.f, the point is mandatory. – Erwan Daniel Mar 11 '20 at 10:41
  • @ErwanDaniel You are perfectly right. Corrected it. Thanks. – Eraklon Mar 11 '20 at 10:46
  • `float` in vanadic args is prompted to `double` (since c99/c+11). Also `int` to `float` conversion may trigger lose precision warning because it is actually may lose precision. No sense to make `float` here. – Askold Ilvento Mar 11 '20 at 10:58
  • @ErwanDaniel: Why use `float` rather than `double`? The question does not request it. – Eric Postpischil Mar 11 '20 at 11:18
  • @EricPostpischil No one said to use a float or double. It's just to show that 400.0 makes double and not a float, to avoid any confusion. But AskoldIlvento is explaning just before you why to use double rather than float. – Erwan Daniel Mar 11 '20 at 11:40