We have now met the spec we set out to do with the code in stock4.eof2.c
The code we have will work fine as long as the user behaves reasonably and always "does the right thing".
But what if they don't? What can the user do wrong?
One thing the user can do is mistype the input, and say enters 0 for the denominator of a stock price. What happens in the program?
ee150:wiliki:22> a.outEnter number of shares(EOF to quit): 57Enter stock selling price as whole numerator denominator: 11 3 0Enter stock purchase price as whole numerator denominator: 9 1 4You have 57 shares of stockselling at $11 3/0which you bought at $9 1/4Enter number of shares(EOF to quit):You bought stock for $527.250000.The value of your portfolio is $++.000000Your net profit is $++.000000We can go back to the algorithm and modify it to make sure the data entered is ok before we proceed:
Initialize the portfolio cost and portfolio value Get the number of shares for the first stock while there are more stocks to proccess Get the selling price for the stock Get the purchase price for the stock Print the data values for the stock if the data entered is ok Accumulate the portfolio cost for the stock Accumulate the portfolio value for the stock otherwise print an error message and ignore the stock. Get the number of shares for the next stock Compute the profit Print the resultWe need a statement that does one thing if a condition is true, and something else if it is false. Such a statement is called an if statement. See If/Else.
The code is in stock5.c
1. We have implemented the data check in the if condition as a function, data_ok(). This hides the details of how we check the validity of the data. In the algorithm for main(), all we care about is testing if the data is valid.2. We define Macros for TRUE and FALSE, and use them in the function, data_ok().
we have only checked the validity of the selling price data. What about the buying price?
The check for the buying price is the same as the check for the selling price - we can use the function data_ok() for that as well.
We could write:
if( data_ok(sell_whole,sell_numer,sell_denomin)) { if( data_ok(buy_whole,buy_numer,buy_denomin)) { /* Calculate portfolio cost */ ... } else /* the buying price is bad */ } else /* the selling price is bad */Or we can combine both tests into a single condition expression as:
if( data_ok(sell_whole,sell_numer,sell_denomin) && data_ok(buy_whole,buy_numer,buy_denomin)) { /* Calculate portfolio cost */ ... } else /* the price is bad */The && operator is a Logical Operator.