svetlozar_kirkov

Decimal Precision Sum (Exercise)

Sep 28th, 2014
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.18 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ConsoleTesting
  6. {
  7.     class ConsoleTesting
  8.     {
  9.         static void Main()
  10.         {
  11.             decimal sum = 1;
  12.             decimal precision = 0.001M;
  13.             for (int i = 0, j = 2; i < Int32.MaxValue; i++,j++)
  14.             {
  15.                 if (i % 2 != 0)
  16.                 {
  17.                     decimal temp = (decimal)1 / j;
  18.                     if (temp < precision)
  19.                     {
  20.                         Console.WriteLine(sum.ToString("N3"));
  21.                         return;
  22.                     }
  23.                     else
  24.                     {
  25.                         sum -= temp;
  26.                     }
  27.                 }
  28.                 else
  29.                 {
  30.                     decimal temp = (decimal)1 / j;
  31.                     if (temp < precision)
  32.                     {
  33.                         Console.WriteLine(sum.ToString("N3"));
  34.                         return;
  35.                     }
  36.                     else
  37.                     {
  38.                         sum += temp;
  39.                     }
  40.                 }
  41.                
  42.             }
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment