sylviapsh

Compare floating-point numbers with certain precision

Dec 26th, 2012
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.11 KB | None | 0 0
  1. using System;
  2. class CompareFloatingNums
  3. {
  4.   static void Main()
  5.   {
  6.     //Telerik Academy. Primitive Data Types and Variables
  7.  
  8.     //Write a program that safely compares floating-point numbers with precision of 0.000001.
  9.     //Examples: (5.3 ; 6.01) -> false;  (5.00000001 ; 5.00000003) -> true
  10.  
  11.     //Read the 2 decimal numbers from the console
  12.     decimal firstNum = decimal.Parse(Console.ReadLine()),
  13.             secondNum = decimal.Parse(Console.ReadLine()),
  14.  
  15.     //Declare the precision for the comparison
  16.             precision = 0.000001m,
  17.  
  18.     //Round the numbers to the 6th sign after the decimal point
  19.             roundedFirstNum = Math.Round(firstNum, 6),
  20.             roundedSecondNum = Math.Round(secondNum, 6);
  21.  
  22.     //Do a check for equality within the required precision. Absolute value is checked.
  23.     bool equalityCheck = Math.Abs(roundedFirstNum - roundedSecondNum) <= precision;
  24.  
  25.     //Print the results on the console
  26.     Console.WriteLine("The numbers {0} and {1} are {2} with precision of {3}", roundedFirstNum, roundedSecondNum, equalityCheck ? "equal" : "not equal", precision);
  27.   }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment