Trying to check if this program's logic is off

Mar 19, 2018 at 4:01am
I have to write a program to calculate the batting average and slugging percentage of a baseball player (using random number generation to simulator a few thousand times at the bat), and I'm given a percentage for the probability of an out, a walk, a single, double, triple, and home run. The batting average seems to calculate correctly but the slugging percentage consistently comes in over 1.0...which seems incorrect. Any idea if you can spot something wrong with my logic here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<iostream>
#include<cstdlib>
#include <ctime>

using namespace std;

int main(){
	srand(time(NULL));
	
	int battingCounter = 0,
		hitProbability,
		totalBats,
		totalHits,
		totalOuts = 0,
		totalWalks = 0,
		totalSingles = 0,
		totalDoubles = 0,
		totalTriples = 0,
		totalHomeRuns = 0;
	double battingAvg,
		sluggingPercent;
		
	for(; battingCounter <= 5000; battingCounter++){
		hitProbability = 1 + rand() % 100;
		if(hitProbability >= 0 && hitProbability <= 35)
			totalOuts++;
		else if(hitProbability >= 36 && hitProbability <= 51)
			totalWalks++;
		else if(hitProbability >= 52 && hitProbability <= 71)
			totalSingles++;
		else if(hitProbability >= 72 && hitProbability <= 86)
			totalDoubles++;
		else if(hitProbability >= 87 && hitProbability <= 95)
			totalTriples++;
		else if(hitProbability >= 96 && hitProbability <= 100)
			totalHomeRuns++;
	}
	totalHits = totalWalks + totalSingles + totalDoubles + totalTriples
				+ totalHomeRuns;
	totalBats = battingCounter;
				
	battingAvg = static_cast<double>(totalHits)/
			(static_cast<double>(totalBats) - static_cast<double>(totalWalks));
			
	sluggingPercent = static_cast<double>(totalSingles + (2 * totalDoubles) + (3 * totalTriples) + (4 * totalHomeRuns))/(static_cast<double>(totalBats) - static_cast<double>(totalWalks));
									
	cout<<battingAvg<<endl;
	cout<<sluggingPercent;
	return 0;
Last edited on Mar 19, 2018 at 4:01am
Mar 19, 2018 at 9:11am
Add a line outputting the values used in line 45. Use your own eyes to check if the data is bad, or the calculation bad.
Topic archived. No new replies allowed.