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.

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
@ErwanDaniel You are perfectly right. Corrected it. Thanks.
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.
@ErwanDaniel: Why use float rather than double? The question does not request it.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.