diff --git a/MathTests.cs b/MathTests.cs index ab05ffb..fdcb9c4 100644 --- a/MathTests.cs +++ b/MathTests.cs @@ -49,8 +49,8 @@ public void SolveQaudratic_WithPositive_C_Argument_Should_ReturnOneSameRoot() var result = QuadraticHelper.Solve(a, b, c); // Assert - result.Length.ShouldBe(2); - result[1].ShouldBe(result[0]); + result.Length.ShouldBe(1); + result[0].ShouldBe(result[0]); } [Fact] @@ -74,4 +74,24 @@ public void SolveQaudratic_WithPositive_A_Argument_Should_NotBeNull() } } + + [Theory] + [Trait("Category", "Unit")] + [InlineData(double.NaN, 2, 3, "Argument a is incorrect")] + [InlineData(4, double.NaN, 3, "Argument b is incorrect")] + [InlineData(5, 2, double.NaN, "Argument c is incorrect")] + public void SolveQaudratic_With_A_NaN_Argument_Should_ThrowException(double a, double b, double c, string messageError) + { + + // Act + try + { + var result = QuadraticHelper.Solve(a, b, c); + } + catch (Exception e) + { + // Assert + e.Message.ShouldBe(messageError); + } + } } diff --git a/QuadraticHelper.cs b/QuadraticHelper.cs index ecffd6e..03644d5 100644 --- a/QuadraticHelper.cs +++ b/QuadraticHelper.cs @@ -4,7 +4,9 @@ public static class QuadraticHelper { public static double[] SolveIncompleteQuadraticEquation(double b) { - if (b < 0) + ValidateDoubleParameter(b, "Argument b is incorrect"); + + if (b.CompareTo(0) < 0) return new double[0]; var res = Math.Sqrt(b); @@ -13,19 +15,39 @@ public static double[] SolveIncompleteQuadraticEquation(double b) public static double[] Solve(double a, double b, double c) { - if (a == default) - throw new ArgumentException("Argument a can not be 0"); - - + + ParametersValidation(a, b, c); + double d = b * b - 4 * a * c; - if (d.EqualsExact(0)) - throw new ArgumentException("Diskriminant is 0"); + if (d.CompareTo(0) < 0) + return new double[0]; + else if (d.CompareTo(0) == 0) + { + var x1 = (-b) / 2 * a; + return new double[] { x1 }; + } else + { + var x1 = (-b + Math.Sqrt(d)) / 2 * a; + var x2 = (-b - Math.Sqrt(d)) / 2 * a; + return new double[] { x1, x2 }; + } + } - var x1 = (-b + Math.Sqrt(d)) / 2 * a; - var x2 = (-b - Math.Sqrt(d)) / 2 * a; + private static void ParametersValidation(double a, double b, double c) + { + if (a.EqualsExact(0)) + throw new ArgumentException("Argument a can not be 0"); - return new double[] { x1, x2 }; + ValidateDoubleParameter(a, "Argument a is incorrect"); + ValidateDoubleParameter(b, "Argument b is incorrect"); + ValidateDoubleParameter(c, "Argument c is incorrect"); + } + + private static void ValidateDoubleParameter(double val, string errorMessage) + { + if (!double.IsFinite(val) || double.IsNaN(val)) + throw new ArgumentException(errorMessage); } } }