开发者

Scanner fractionSum finishing part

I need to write a method where the parameter accepts an integer (n in this case) and returns the sum of the first n terms of the sequence as a double value. So say I put fractionSums(5); the output would be

1+...+1/5 which would then equal to something like 2.8333~.(final result)

what I have now is:

开发者_开发百科
public static void main(String[] args) {
  fractionSums(5);
}

public static void fractionSums(int n) {
  Scanner console = new Scanner(System.in);

  System.out.print("How many terms do you have? ");
  int totalterms = console.nextInt();
}

I'm stuck here and don't know how to go further than this and where to implement n. How would you recommend me on proceeding with this. Do I have to edit this question in anyway?


Write your input more explicitly and take a look at the pattern. Ask yourself, where are those numbers coming from?


Try placing the scanner in main and println in main. You should create a method (you've called it fractionSums() here ) and invoke it to calculate the fraction sum and return a double (pass the int n to the method). That method can be either recursive or iterative, but since you say "I need to write a method where the parameter accepts an integer (n in this case) and returns the sum of the first n terms of the sequence," you should make the method return something (either a float or a double).

HTH :)


Define a double variable to hold the result, and initialise it to zero.

You will have to sum totalTerms terms. You can start by writing a loop (for example, a for loop) that will run for totalTerms iterations.

In iteration 1, you need to add 1/1 to the result. In iteration 2, you need to add 1/2. In iteration 3, you need to add 1/3, and so on. You can see there's a relation between the iteration number and the term you need to add.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜