A
A
Axretit2022-03-01 18:09:19
C++ / C#
Axretit, 2022-03-01 18:09:19

Why is the result of the calculation integer?

621e353540bf2658590792.png
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

3 answer(s)
O
oleg_ods, 2022-03-01
@Axretit

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);

In this expression, the pow() function returns a real number, so the calculation result will be correct.
Also pay attention to the order of operations. For example, in the expression:
x = (5/2 + pow((r - q), 2)) / (p + 12);

5/2 will be calculated according to the rules of integer division and will give 2(int).

V
vreitech, 2022-03-01
@fzfx

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

will return an integer response.
and only when you have a pow function in the sequence of operations that always returns a real result, do you start to perform addition, subtraction, multiplication and division operations on real numbers (starting from the place where the result of the pow function is used).
if you need some operation to occur on real operands, then you should use real literals or real variables as operands.
if I'm not confused, in C++ you can add a dot to the number at the end. something like:
(99/7.)-222*2
either use the exponential notation of the number. options are presented, for example, here:
https://en.cppreference.com/w/cpp/language/floatin...

R
rPman, 2022-03-01
@rPman

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 question

Ask a Question

731 491 924 answers to any question