0

I'm trying to print the following series in a table:

m(i) = 1/2 + 2/3 + ... + i/(i + 1)

The table would look like the one below:

i m(i) 1 0.5000 2 1.1667 ... 19 16.4023 20 17.3546

But the table I'm currently getting is:

1 0.5 2 0.6666666666666666 3 0.75 4 0.8 5 0.8333333333333334 6 0.8571428571428571 7 0.875 8 0.8888888888888888 9 0.9 10 0.9090909090909091 11 0.9166666666666666 12 0.9230769230769231 13 0.9285714285714286 14 0.9333333333333333 15 0.9375 16 0.9411764705882353 17 0.9444444444444444 18 0.9473684210526315 19 0.95 20 0.9523809523809523

The code I have so far is below:

public class Help {

public static double printSeries(int ch1, int ch2){

    for (int i=ch1; i <= ch2; i++){
        double iPlusOne = i+1;
        double mi =+ i/iPlusOne; 
        System.out.println(i + "      "  + mi);

    }// end of for loop
    return 0.00;
}// end of printSeries method

public static void main(String args[]){
    printSeries(1, 20);
}// end of main method

}// end of class

For some reason mi isn't adding mi to itself. Is there something wrong with the syntax of my code?

Thanks

2 Answers2

1

Syntax error. Where you have =+ should be +=. The compiler does not object because it's still a valid statement.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

Dude you declared within the loop itself so on each iteration it's creating a new mi variable . Try like this

public class Help {

public static double printSeries(int ch1, int ch2){
    double mi=0;
    double iPlusOne=0;
    for (int i=ch1; i <= ch2; i++){
        iPlusOne = i+1;
        mi += i/iPlusOne; 
        System.out.println(i + "      "  + mi);

    }// end of for loop
    return 0.00;
}// end of printSeries method

public static void main(String args[]){
    printSeries(1, 20);
}// end of main method

}// end of class

Output :

1      0.5
2      1.1666666666666665
3      1.9166666666666665
4      2.716666666666667
5      3.5500000000000003
6      4.4071428571428575
7      5.2821428571428575
8      6.171031746031746
9      7.071031746031746
10      7.980122655122655
11      8.896789321789322
12      9.819866244866246
13      10.748437673437675
14      11.681771006771008
15      12.619271006771008
16      13.560447477359244
17      14.504891921803688
18      15.45226034285632
19      16.40226034285632
20      17.354641295237272
Paul Richter
  • 10,908
  • 10
  • 52
  • 85
Bala.Raj
  • 1,011
  • 9
  • 18