I need to know the price of all the offices that a company hires, knowing that you pay per office and there can be room for two workers per room, the problem is that I cannot use libraries or if...
monthlyPrice = oficePrice * (workers/2);
monthlyPrice = 100 * (7 / 2) = 350$
I need to either round up or find me another mathematical formula.
it could be done with a realtointegrer, i don´t now... :(
Thanks. Pablo.
CodePudding user response:
The simpliest way to round a floating point number x
is as follows:
return (int)(x 0.5);
CodePudding user response:
I would suggest that you use the /
and %
operators.
/
will give you the integer section (left side of decimal point) for a division operation.
%
will give you the remainder section (right side of the decimal point) of a division operation.
e.g.
7/2
gives 3
7%2
gives 1
You can then decide whether you wish to round up the result depending on the value returned by using %
.
Ah I see that you're not allowed to use the if ... else ...
construct. What about ... ? ... : ...
?
CodePudding user response:
For money I would use fixed point.
//one cent is minimum we care
#define MULT (100)
#define MAKE_FIXED(d) ((int32_t)(d * MULT))
#define MAKE_REAL(f) (((double)(f)) / MULT)
int32_t mulf(int32_t a, int32_t b)
{
int64_t part = (int64_t)a * b;
return part/MULT;
}
int32_t divf(int32_t a, int32_t b)
{
int64_t part = ((int64_t)a * MULT) / b;
return part;
}
int main(void)
{
int32_t officeprice = MAKE_FIXED(100);
int32_t workers = MAKE_FIXED(7);
printf("%f\n", MAKE_REAL(mulf(officeprice, divf(workers,MAKE_FIXED(2)))));
}