# Arithmetic sequence java?

How come this isn't outputting the right answer?

First term is 3.9

Second term is 1.4

number of terms in sequence is 4

formula is: (4/2) * (2(3.9) + -2.5(4-1))

It should print out 0.6 but I keep getting 0.5999999999999996.

Code:

public static void main(String[] args)

{

Scanner keyboard = new Scanner (System.in);

double first_term, second_term, constant_difference, number_of_terms, sum = 0.0;

System.out.print("What is the first term in the sequence? ");

first_term = keyboard.nextDouble();

System.out.print("What is the second term in the sequence? ");

second_term = keyboard.nextDouble();

System.out.print("Enter the number of terms in the sequence: ");

number_of_terms = keyboard.nextInt();

constant_difference = second_term - first_term;

//Calculates the sum using the arithmetic formula

sum = (number_of_terms/2) * (2*(first_term) + constant_difference*(number_of_terms - 1));

System.out.println("\nThe sum of the sequence is " + sum);

}

### 3 Answers

- Link HLv 68 years agoBest Answer
many decimal numbers cannot be precisely represented as a binary number of limited length. this is called error in precision, or depending on how it manifests, as truncation or round-off error. it is an unavoidable artifact of calculation with a computer.

- ?Lv 48 years ago
floating point numbers do that sometime.. that is the equivalent to .6 .. if you really want to you can round it off with printf, or a simple rounding method.

- 8 years ago
system.out.println(""\nThe sum of the sequence is " + "string.Format("{0:0,0.##}", sum))

maybe?