문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top