Advertisement
Shailrshah

Evaluating Sum of a Series

Aug 24th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.81 KB | None | 0 0
  1. import java.io.*;
  2. class Calc{
  3.     private static String getInput(String prompt){
  4.         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
  5.         System.out.print(prompt);
  6.         System.out.flush();
  7.         try{
  8.             return stdin.readLine();
  9.         }catch(Exception e){
  10.             return "Error: " + e.getMessage();
  11.         }
  12.     }
  13.     public static void main(String[] args){
  14.         float sum = 1;
  15.         String input = getInput("Enter the limit: ");
  16.         int n = Integer.parseInt(input);
  17.         if(n>0){
  18.             System.out.print("1/(1.0)^2");
  19.             for(float i=2; i<=n; i++){
  20.                 System.out.print(" + 1/("+i+")^2");
  21.                 sum += 1/(i*i);
  22.             }
  23.             System.out.print(" = " +sum);
  24.         }
  25.         else
  26.             System.out.print("Error: Not a positive number.");
  27.     }
  28. }
  29.  
  30. // Output:-
  31. // Enter the limit: 5
  32. // 1/(1.0)^2 + 1/(2.0)^2 + 1/(3.0)^2 + 1/(4.0)^2 + 1/(5.0)^2 = 1.4636111
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement