Answer the question
In order to leave comments, you need to log in
Why is the result of the calculation integer?
There are integer variables and there is x - real. x is the end result.
I noticed that if you write all the actions separately, in separate lines, then at the end x , whatever it may be, remains an integer. For example: x = 1/13; x = 0;
s = pow((r - q),2);
a = a*s;
p = p + 12;
x = a/p;
(all variables of type int, except for x , x of type double)
And if all actions are written in one line, then x remains real and the answer is correct.
x = (a * pow((r - q), 2)) / (p + 12);
(all variables of type int except x , xtype double)
What is the pattern?
Answer the question
In order to leave comments, you need to log in
If only integer values participate in the expression, then the result will be integer.
If the expression contains real numbers, then the result will be real.
x = (a * pow((r - q), 2)) / (p + 12);
x = (5/2 + pow((r - q), 2)) / (p + 12);
the regularity is that if the operation of addition, subtraction, multiplication or division is carried out on integer operands (that is, not on real ones), then an integer result is returned upon its execution.
so operations:
71/3
67+5
(99/7)-222*2
(99/7.)-222*2
pow returns type double
in the first case you convert it to int and all subsequent operations are with integral types, incl. and /,
and in writing to a string, it makes the left side of the expression before / a double type, which means that division is also called for a double type
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question