Advertisement
sylviapsh

Sum 1 With 1 Divided By N With Precision of 0.001

Dec 28th, 2012
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.52 KB | None | 0 0
  1. using System;
  2. class Sum1With1DividedByNWithPrecision
  3. {
  4.   static void Main()
  5.   {
  6.     //Write a program to calculate the sum (with accuracy of 0.001): 1 + 1/2 - 1/3 + 1/4 - 1/5 + ...
  7.     Console.Write("Please enter the end number of the interval:");
  8.     int numberOfelements = int.Parse(Console.ReadLine());
  9.     decimal sum = 1m;
  10.     int i = 0;
  11.     for (i = 2; i <= numberOfelements; i += 2)
  12.     {
  13.       sum += (1 / (decimal)i) - (1 / (decimal)(i + 1));
  14.     }
  15.     Console.WriteLine("The sum is: {0:.000}", sum);
  16.   }
  17. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement