I am doing a homework project that requires this:
Below you will find the code I wrote to calculate the square root of a number using the Newton-Raphson method. Include it in your project. For this project, your job will be to write a test harness that checks the code I wrote. Carefully read the method prologue to understand how this function should work. Your test run will provide a loop that:
- Asks the user to enter a test value.
- Returns user input. If zero is entered, your program will print a report and exit.
- Calls the Sqrt method provided in this project and stores the return value in a double variable.
- Calls the Sqrt method, which is built into the Math class and stores the return value in a second double variable.
- Compare these two values to make sure they are equal.
- When the user indicates that they have been done (by entering a zero), display a report that shows this information: * How many test cases you performed * How many passed * How many failed
So, I did all this without any problems after about 15 minutes, however, for an extra loan, he asks us to find out what is wrong with his Sqrt method and fix it so that its return value is equal to the return value of the Math.Sqrt.NET Framework . I can’t find the problem in his method, and I want to find it, so I was wondering if anyone could point me in the right direction, what is the problem with his Sqrt method? Thanks.
Here is my complete code:
double userInput = 0.0;
double debrySqrtReturnValue = 0.0;
double dotNetSqrtReturnValue = 0.0;
int testCasesExecuted = 0;
int testsPassed = 0;
int testsFailed = 0;
bool isEqual = false;
do
{
Console.Write("Please enter a positive integer value: ");
userInput = double.Parse(Console.ReadLine());
if (userInput != 0)
{
debrySqrtReturnValue = Sqrt(userInput);
dotNetSqrtReturnValue = Math.Sqrt(userInput);
Console.WriteLine("The square root of {0} is: {1}", userInput, debrySqrtReturnValue);
Console.WriteLine("The real square root of {0} is: {1}\n", userInput, dotNetSqrtReturnValue);
if (debrySqrtReturnValue == dotNetSqrtReturnValue)
isEqual = true;
else
isEqual = false;
if (isEqual)
testsPassed++;
else
testsFailed++;
testCasesExecuted++;
}
} while (userInput != 0);
Console.WriteLine("\n\n--------------------------------Report---------------------------------");
Console.WriteLine("test cases excecuted: {0}", testCasesExecuted);
Console.WriteLine("tests passed: {0}", testsPassed);
Console.WriteLine("tests failed: {0}", testsFailed);
Console.ReadLine();
}
static double Sqrt(double number)
{
const int FIRST_APPROX = 2;
const double EPS = 0.001;
double xN = 0;
double xNPlus1 = FIRST_APPROX;
do
{
xN = xNPlus1;
xNPlus1 = xN - ((xN * xN - number) / (FIRST_APPROX * xN));
} while (Math.Abs(xNPlus1 - xN) > EPS);
return xN;
}
}