As you mentioned Bloodday , it might be more efficient to use the same type for all operations. .. at the end of the day, what do you use whole to store hours? Are there not fractions of hours? What happens if a worker has worked 63 minutes? Or 111 minutes?
However, because of the design of your code, it is " necessary " that the variable horas
is an integer since you use this variable both to control the flow of the program and to make calculations.
Since floating-point numbers are known for the inaccuracy they have to reflect certain numbers (for example, it is impossible to express exactly the number 0.1, so an approximation is made); this imprecision makes comparisons for equity in floating-point numbers is discouraged, because it could be the case that 0.1 == (1.0 / 10.0)
turns out to be false!
This makes " mandatory " the integer type for horas
because you use a comparison of equity (well, inequality in this case); surely compare the inequality of horas
as double
directly against -1.0
no problems but if horas
was used in calculations before making the inequality check could fail the condition even if supposedly should have been fulfilled.
That said, I advise you to use a variable double
for hours and a control variable for the flow, for example: after the operation ask:
¿Desea continuar? (S/N)
And use a variable char
, so the variable horas
will have a sole responsibility .
To finish, you do not need type transformations in operations:
static_cast<double>(horas) * tarifa
static_cast<double>(horas - horasMax) * (tarifa * excedente)) + (static_cast<double>(horasMax) * tarifa
Since the integers will be promoted to double
implicitly (the highlight is mine):
Conversions
If the operand passed to an arithmetic operator is an integral value or an enumerated without scope, before any other action, the operand is promoted to integral.
For binary operators (except offsets), if the promoted operands have different types, additional conversion rules are applied, known as "usual arithmetic conversions" in order to produce a common type :
- If any of the operands is an enumerated with scope, no conversion is made: both operands must have the same type.
- Otherwise, if one of the operands is
long double
the other operand is converted to long double
.
-
Otherwise, if one of the operands is
double
the other operand is converted to double
.
- Otherwise, if one of the operands is
float
the other operand is converted to float
.
Therefore, if you decide to keep the whole type for horas
, you can calmly remove the explicit conversion of your code because there is already an implicit conversion; removing those unnecessary static_cast
will make the code a little easier to read.