C++ Out 58.0% Walk 9.7% Single 22.0% Double 6.1% Triple 2.5% Home Run 1.7% Based
ID: 3846113 • Letter: C
Question
C++
Out
58.0%
Walk
9.7%
Single
22.0%
Double
6.1%
Triple
2.5%
Home Run
1.7%
Based on the above percentages, write a program to simulate Alex stepping up to the plate 1000 times and count and display the number of outs, walks, singles and so on. Then calculate and display his batting average:
number of hits
batting average = ----------------------------------
Times at bat – number of walks
Enclose your logic in a do while which will ask the user if he or she wishes to continue and accepts a char value of Y or N as an answer. Run and capture execution samples of at least two simulations.
Out
58.0%
Walk
9.7%
Single
22.0%
Double
6.1%
Triple
2.5%
Home Run
1.7%
Explanation / Answer
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int timeAtBat;
double out, walk, single, doubleHits, triple, homeRun, battingAverage, sluggingPercentage;
double numberOfHits, numberOfWalks;
srand(time(NULL));
do
{
imeAtBat = 1000 + rand(); //random number generator to find out times at Bat
cout << "Time at Bat: " << timeAtBat << endl;
//don't know what to do with this information
int hitOrMiss = 1 + rand() % 100; //random number generator from 1 - 100 to find probabilty of hit or miss
cout << "hit or miss: " << hitOrMiss << endl << endl;
//calculate probability of hit miss based on chart
out = 0.58 * timeAtBat;
walk = 0.097 * timeAtBat;
single = 0.22 * timeAtBat;
doubleHits = 0.061 * timeAtBat;
triple = 0.025 * timeAtBat;
homeRun = .017 * timeAtBat;
cout << "Out: " << out << endl;
cout << "Walk: " << walk << endl;
cout << "Single: " << single << endl;
cout << "Doubles: " << doubleHits << endl;
cout << "Triples: " << triple << endl;
cout << "Home Runs: " << homeRun << endl << endl;
numberOfHits = single + doubleHits + triple + homeRun;
numberOfWalks = out + walk;
battingAverage = numberOfHits / (timeAtBat - numberOfWalks);
sluggingPercentage = (single + doubleHits * 2 + triple * 3 + homeRun * 4) / (timeAtBat - numberOfWalks);
cout << "Number of Hits: " << numberOfHits << endl;
cout << "Number of Walks: " << numberOfWalks << endl;
cout << setprecision(3) << fixed << "Batting average: " << battingAverage << endl;
cout << "Slugging %: " << sluggingPercentage << endl;
}
system("pause");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.