Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions MathTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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);
}
}
}
42 changes: 32 additions & 10 deletions QuadraticHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
}
}