Why do not you print the 4.5 on the first operation and the 2.5 on the second one?
Because setprecision
only works with decimal types, that is, with float
and double
.
In your case, all the numbers involved in the operation are of int
, then the result will be, yes or yes, of type int
and, therefore, will not have decimals.
As you said @GusZL the solution is to get the result is decimal. However, in C ++ I am not in favor of using a conversion bareback . This is not C and in C ++ there are 4 special functions to perform conversions that are much more powerful and secure than those used in C. You can get more information on this topic in this other question .
For this case it would be worth with static_cast
:
static_cast<double>(5)/2+20%6
Notice that I only force the conversion of a number instead of the result of the operation ... if I did this:
static_cast<double>(5/2+20%6)
The 5/2
operation would be performed on integer types and would return 2
instead of 2.5
. On the other hand, as soon as one of the two numbers is double
, the compiler will perform a conversion of type int
to double
before executing the operation:
numerador decimal: 5.0/2 => 5.0/2.0 = 2.5
denominador decimal: 5/2.0 => 5.0/2.0 = 2.5
ambos tipos enteros: 5/2 = 2 -> se descartan los decimales
Another possibility is to write the numbers that directly interest in decimal notation so that your native type is double
:
opción 1: 5.0/2.0
~~
opción 2: 5/2.0
~~
opción 3: 5.0/2.0
~~ ~~