Trying to check if this program's logic is off
Mar 19, 2018 at 4:01am UTC  
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#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 UTC  
 
Mar 19, 2018 at 9:11am UTC  
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.