In: Computer Science
IN C++
The price of stocks is sometimes given to the nearest eighth of a dollar; for example, 29 7/8 or 89 1/2. Write a program that computes the value of the user’s holding of one stock. The program asks for the number of shares of stock owned, the whole dollar portion of the price and the fraction portion. The fraction portion is to be input as two int values, one for the numerator and one for the denominator. The program then outputs the value of the user’s holdings. Your program should allow the user to repeat this calculation as often as the user wishes. Your program will include a function definition that has three int arguments consisting of the whole dollar portion of the price and the two integers that make up the fraction part. The function returns the price of one share of stock as a single number of type double.
TEST RUN:
Enter stock price and number of shares, please.
Enter price as integers: dollars, numerator, denominator.
30
7
8
Enter number of shares held.
200
200 shares of stock with market price 30 7/8
have value $6175.00
Do you wish to do another? y
Enter stock price and number of shares, please.
Enter price as integers: dollars, numerator, denominator.
57
3
8
Enter number of shares held.
150
150 shares of stock with market price 57 3/8
have value $8606.25
Do you wish to do another? n
We just have to convert the mixed fraction into a proper fraction and multiply it by the number of stocks.
Here's the code.
#include <iostream>
using namespace std;
double calculatePrice(int dollars, int numerator, int
denominator){
double res = 0.0;
res = static_cast<double>(dollars * denominator + numerator)
/ (denominator);
return res;
}
int main() {
int dollars, numerator, denominator;
double value = 0, costOfOneShare, numOfShares;
char choice = 'y';
while(choice == 'y' || choice == 'Y'){
cout << "Enter price as integers: dollars,
numerator, denominator" << endl;
cin >> dollars;
cin >> numerator;
cin >> denominator;
costOfOneShare = calculatePrice(dollars, numerator,
denominator);
cout << "Enter number of shares" <<
endl;
cin >> numOfShares;
cout << numOfShares << " shares of stock
with market price " << dollars << " " <<
numerator << "/" << denominator;
cout << " have value " << numOfShares *
costOfOneShare << endl;
cout << "Do you wish to do another?" <<
endl;
cin >> choice;
}
return 0;
}
Here are the screenshots of the code and the output.
Let me know if you have any doubts in the comments. Please upvote if the answer helped you.