programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Rounding off a double value to the nearest integer

Khusbu Sinha
Ranch Hand
Posts: 117
1
I am writing a program to calculate the averages of even and odd numbers in an array. The averages should be rounded off to the nearest integers. My program truncates the decimal part instead of rounding it  off to the nearest integer.

Test case example:
Enter the array size:
6
Enter the array elements:
13 17 23 56 28 32

Output:
The average of even numbers= 38
The average of odd numbers= 17

The average 38.6 is rounded off to 38 instead of 39
The average 17.6 is rounded off to 17 instead of 18

My code for the calculation is as follows:

Liutauras Vilda
Sheriff
Posts: 4917
334
• 1
You problem probably appears when you do the division, an integer division.

13 + 17 + 23 = 53
53 / 3 = 17
(int) 17 you get 17

You need to divide by 3.0 in order to get an answer in double, then round, then cast to int.

Khusbu Sinha
Ranch Hand
Posts: 117
1
Thanks for the correction.

Campbell Ritchie
Marshal
Posts: 56541
172
You have some badly‑named variables there: c1 and a. Nobody can read those names and know what they mean. Also what type are they? Remind yourself of the rules for rounding in division and see whether they differ for integer arithmetic and floating‑point arithmetic.

Khusbu Sinha
Ranch Hand
Posts: 117
1
c1 and c2 are for calculating the sum of the even and odd elements of the array respectively and a[] is for the array. c1, c2 and a[] are of type int.

Khusbu Sinha
Ranch Hand
Posts: 117
1
I changed n1 and n2 to double for the division to be in double.

Liutauras Vilda
Sheriff
Posts: 4917
334
What Campbell was saying is, that if one requires a clarification what they mean, that suggests that variable doesn't reveal its intent.

How about changing c1 to sumOfEvenNumbers, and c2 to sumOfOddNumbers? Do you think Campbell would have asked you what variable 'sumOfEvenNumbers' represent? He'd look silly if he would, wouldn't he?

Always name variables clearly, try to avoid abbreviations as fn (guess what it means?) - nope, I had in mind fullName. See? It is clear right away.
Same applies to method names, class names.

Khusbu Sinha
Ranch Hand
Posts: 117
1
Sorry for my vague reply. I could understand what he meant.
I've changed the variable names to `sumOfEven` and `sumOfOdd` respectively and will keep this nomenclature in mind.

Liutauras Vilda
Sheriff
Posts: 4917
334
• 1
No worries

 Don't get me started about those stupid light bulbs.