user1588867
user1588867

Reputation: 67

Java adding series of fractions together

So, I have a question in my assignment. It's "Add fractions (1/10)+(2/9)+(3/8)+(4/7)+(5/6)+(6/5)+(7/4)+(8/3)+(9/2)+(10/1) together and the output should be 4 decimal points". I've written a loop using 1 and 10 value increasing and decreasing as I go. It doesn't seem to be coming up with the correct answer. It should be 22.218650... etc because I haven't limited the decimal places yet, but it doesn't give the correct answer. The output I'm getting is 18.0.

public class AddThemUp {
  // instance variables - replace the example below with your own

  public static void main(String [] args) {
    int i;
    int numer = 1;
    int denom = 10;
    double addUp = 0.0;

    for (i = 1; i <= 10; i++) {
        addUp = (numer / denom) + addUp;
        numer++;
        denom--;
    }
    System.out.println(addUp);
  }
} 

The addUp println is just to see if the math is working properly before I try and figure out the decimal place delimiter. Am I using the double improperly or should the numer and denom be double as well? Any help would be appreciated.

Upvotes: 1

Views: 2898

Answers (2)

Yogendra Singh
Yogendra Singh

Reputation: 34367

Its converting your division (numer/denom) to int so all decimal values in the result are lost. Convert one of the value to decimal e.g. double in your computation e.g. below:

 addUp = ((double)numer / denom) + addUp;

You will get your expected result.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're doing int division which always returns an int -- not the result you want. You need to do double division for this to work. Cast the numerator or denominator of the fraction to double:

((double) numerator / denominator)

Upvotes: 1

Related Questions