Note that division is defined to be integer division when both operands are integers. In our program, both numerator and denominator are declared to be integers, so the result of the division is also an integer. With integer division, 3/8 is 0. This we get the price to be 11.0000.
What we would like to do is just change the type of these values for the purpose of this calculation only. C provides an operator to do just that: the cast operator. The syntax is:
( <type identifier> ) <variable name>
which we can use anywhere in any expression.
This cast expression DOES NOT change the type of cell used to store
the variable, nor does it change the value stored in that cell.
Instead, it accesses the value in the cell, and converts it to the
requested type to use in the expression.
So, the calculation of price becomes:
price = (sell_whole + (float)sell_numer / (float)sell_denomin);
When we modify the
code,
compile it, and run it, we get the output:
You have 57 shares of XYZ Corp. selling at $ 11 3/8 degug: price = 11.375000 The value of the stock is $648.375000The price is calculated correctly, and we get the correct answer for the portfolio value. We can then fix the original assignment statement:
/* Calculate portfolio value */
portfolio_value = shares * (sell_whole +
(float)sell_numer / (float)sell_denomin);
and remove the debugging code we inserted
(or just comment it out, in case we need to use it again later -
we will see better ways to do this soon).