Help with rounding ints in an array

Stuck on an issue for an assignment. Problem I'm having is with calculating the average of the data within two arrays, and filling a new array with the results.

1
2
3
4
5
6
7
8
9
//calculate batting average
	void calcBatAvg(int atBats[], int hits[], int batAvg[], int counter) {      

		

		for (int i = 0; i < counter; i++) {
			batAvg[i] = ((atBats[i] * 1000) / hits[i]);
		}
	}



What I'm trying to figure out is how to cause the data placed into the batAvg[] array to round to nearest int during the process, instead of having the decimal fall off. I have to keep the function as-is, and can only use the listed parameters. I thought casting would be an option, but not sure how you would cast data in an array. Will this require another function called within

void calcBatAvg()

to perform the rounding, or am I missing something obvious?
Last edited on
Your equation is entirely int, so fractions are discarded before the result is stored.

You can force floating point math with:
(atBats[i] * 1000.0) / hits[i]

What do you think that could happen, if you add 0.5 to the result?


PS. What if 0 == hits[i]?
You could calculate the average as a float and then round it yourself.

1
2
3
4
5
6
7
8
9
float avg;
for(int i = 0; i < counter; i++) {
    avg = ( (float)atBats[i]  * 1000.0) / (float)hits[i];
    
    // Round here. Lots of ways to do it (multiply avg by ten and look at the last digit is the first thing
    // that comes to my mind. If it's >= 5 add .5 to it and when you cast to an int it will 'round up'

    batAvg[i] = (int)avg;
}
Last edited on
Keskiverto & edge6768,

Already tried those methods, but thanks for the suggestions! The class found out today that there was a typo in the instructions, so I was able to figure it out from that point on. Originally, the impression was that no other data types/parameters were allowed within the provided functions (Only void functions with int parameters), but things have been cleared up, and floats were in fact allowed. Appreciate the help!
Topic archived. No new replies allowed.