0

I'm brand new to to Java and looking with some help. I have an array list as follows:

double number[]={19.1904990290,27.2646233344,51.4850317134}

I've used the following code to sum the array list and print it to the console:

int sumLeft = 0;        
System.out.println("Contents of leftside: " + number);
for(double i: number) sumLeft += i;
System.out.println("sum(left) = " + sumLeft);

and my result is 97. My question is how can I carry this out so my answer is correct?

3 Answers3

1

Define sumLeft as double. This will fix your issue.

Under the hood sumLeft += i; did something like

sumLeft = sumLeft + (int)i;

Therefore the problem you saw.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

Defining sumLeft as a double will solve your problem.

Be aware though that doubles in computer terms have limited precision and will represent your numbers in odd ways. If precision is important you need to use things like BigDecimal.

http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding

Tim B
  • 40,716
  • 16
  • 83
  • 128
0

As you likely know, int means "integer", i.e. whole numbers with no fractional component. Languages will sometimes do implicit type-conversion, so when the variable storing the value is, for example, an int when your numbers are of type double, the portion after the decimal point gets chopped off.

As others have said, changing sumLeft to a double will avoid this.

defect
  • 488
  • 5
  • 16