Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class CompareFloatingNums
- {
- static void Main()
- {
- //Telerik Academy. Primitive Data Types and Variables
- //Write a program that safely compares floating-point numbers with precision of 0.000001.
- //Examples: (5.3 ; 6.01) -> false; (5.00000001 ; 5.00000003) -> true
- //Read the 2 decimal numbers from the console
- decimal firstNum = decimal.Parse(Console.ReadLine()),
- secondNum = decimal.Parse(Console.ReadLine()),
- //Declare the precision for the comparison
- precision = 0.000001m,
- //Round the numbers to the 6th sign after the decimal point
- roundedFirstNum = Math.Round(firstNum, 6),
- roundedSecondNum = Math.Round(secondNum, 6);
- //Do a check for equality within the required precision. Absolute value is checked.
- bool equalityCheck = Math.Abs(roundedFirstNum - roundedSecondNum) <= precision;
- //Print the results on the console
- Console.WriteLine("The numbers {0} and {1} are {2} with precision of {3}", roundedFirstNum, roundedSecondNum, equalityCheck ? "equal" : "not equal", precision);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment