Reputation: 45
I doing a program that will print out the sum and average of a set of numbers. I'm pretty new to java, and I can't seem to figure out how to get the .7 that is supposed to be on the end of the average, I only get .0. I don't think it has to do with my math, I think there is an error in my rounding statement. Could someone point the error out to me? Thanks guys.
public class Program
{
public static void main (String[]args)
{
int a = 475;
int b = 821;
int c = 369;
int d = 562;
int e = a+b+c+d;
double f = e/4;
f=(int)(f*10+.5)/10;
System.out.println("The sum of the four numbers is "+ e + " and the average is "+ f);
}
}
Upvotes: 1
Views: 86
Reputation: 17454
When you have an integer divide by another integer, this is call integer division. The output will the discard the decimal values.
For example:
double v1 = 5/2; //Value of v1: 2.0 (0.5 discarded)
double v2 = 10/3; //Value of v2: 3.0 (0.333 discarded)
An integer division is happening in your codes at this line:
double f = e/4;
Hence, all the decimal values are discarded.
To retain the decimal value, you can simply do one the following (to indicate one of the operand is a decimal value, hence integer division will not occur):
double f = e/4.0;
double f = e/(double)4;
double f = e/4d;
Upvotes: 0
Reputation: 5742
You lost the decimal point because e/4 is an integer. try e/4F to indicate the expression as float number
double f = e/4F;
Upvotes: 0
Reputation: 1485
Instead of double f = e/4;
, do double f = e/4.0;
With e/4
, you divide an int
by an int
, which results in an int
. The result is afterwards assigned to a double
. That's why you don't get decimals in your result.
With e/4.0
, you divide an int
by a double
, which results in a double
.
Upvotes: 3