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?

Était-ce utile?

La solution

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

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top