Write something like this y = x/400.0f or y = (float)x / 400
When dividing into a small negative number I just get 0
-
03-07-2023 - |
Pergunta
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?
Solução
Outras dicas
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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow