Question

In my current program I am having an issue where, when I divide a number by a larger number I am just given 0. For example if I divide -272 by 400 I receive 0.

y=x/400;
printf("%f\n", y);

This is the only piece of code causing issues. x is a negative integer 1-500 and y is initialized as a float.

Where am I going wrong?

Was it helpful?

Solution

Write something like this y = x/400.0f or y = (float)x / 400

OTHER TIPS

The division operation deduces it's result based on the operands. If both operands are int then the result is int. In your case both x and 400 are int so the result of / is int. This int is then converted to float because y is float, but the result was already truncated to int.

You need to convert at least one operand to float:

y = (float) x / 400;

or

y = x / 400.0f
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top