// // Program: stock_value // // Purpose: track value of stock investment as price per share changes. // // Input (from standard input; program will prompt for it): // number of shares (integer) // initial price per share (floating-point) // sequence of updated prices, terminated by control-D // // Output (on standard output): // initial value (number of shares * price per share) // for each updated price, new value, and difference between old // value and new value // #include #include // has setiosflags(), setprecision(2) // Function prototypes -- see comments with function definitions below. void printPrompt(void); void printMoney(double d); // Main program. int main(void) { int shares; double price; double oldval; // total value at previous price double newval; // total value at current price cout << "How many shares?\n"; cin >> shares; cout << "Initial price per share?\n"; cin >> price; oldval = shares * price; cout << "Initial value = "; printMoney(oldval); cout << endl; printPrompt(); while (cin >> price) { // "Loop invariant": oldval is the total value at the previous // price. True every time through the loop. newval = shares * price; cout << "New value = "; printMoney(newval); cout << endl; cout << "You made "; printMoney(newval - oldval); cout << " today!\n"; oldval = newval; printPrompt(); } return 0; } // Function to print prompt for next price. // Post: user has been prompted for next price, with instructions // on how to signal end of input. void printPrompt(void) { cout << "Enter new price per share, or control-D to end:\n"; return; } // Function to print a double as "money". // Post: d is written to standard output, with exactly two decimal // places and preceded by a dollar sign. void printMoney(double d) { cout << setiosflags(ios::showpoint | ios::fixed) << setprecision(2) << d; return; }