Advertisement
AnitaN

02.PrimitiveDataTypesVariables/03.ComparingFloats

Mar 9th, 2014
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. //Problem 3. Comparing Floats
  2. //Write a program that safely compares floating-point numbers with precision eps = 0.000001.
  3. //Note that we cannot directly compare two floating-point numbers a and b by a==b because of the nature of the floating-point arithmetic.
  4. //Therefore, we assume two numbers are equal if they are more closely to each other than a fixed constant eps.
  5.  
  6. using System;
  7.  
  8. class ComparingFloats
  9. {
  10.     static void Main()
  11.     {
  12.         decimal firstNumber;
  13.         decimal secondNumber;
  14.         Console.WriteLine("Enter the first Decimal number :");
  15.         firstNumber = decimal.Parse(Console.ReadLine());
  16.         Console.WriteLine("Enter the second Decimal number :");
  17.         secondNumber = decimal.Parse(Console.ReadLine());
  18.         //Compare First and Second Number with precision eps=0.000001
  19.         bool compare = (Math.Abs(firstNumber - secondNumber) < 0.000001m);
  20.         if (compare)
  21.         {
  22.             Console.WriteLine("The numbers {0} and {1} are equal.", firstNumber, secondNumber);
  23.         }
  24.         else
  25.         {
  26.             Console.WriteLine("The number {0} and {1} are not equal.", firstNumber, secondNumber);
  27.         }
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement