I just wrote my first C# program.
It’s a simple piece of code which solves quadratic equations.
It works with some functions (such as -6×2-6x+12) perfectly, while with others, (4×2-20x+25) it exhibits what I suspect are rounding errors.
I’m completely new to C#, and I can’t see an problems; would someone be able to help me debug this code?
namespace ConsoleApplication {
class Program {
static int ObtainInput(string prompt, bool canBeZero) {
double a = ObtainInput("A? ", false);
double b = ObtainInput("B? ", true);
double c = ObtainInput("C? ", true);
double d, x1, x2;
while (true) {
Console.Write(prompt);
string input = Console.ReadLine();
int result;
bool success = int.TryParse(input, out result);
if (success && (canBeZero || result != 0))
return result;
Console.WriteLine("Invalid input!");
}
// Calculating a discriminant
d = b * b - 4 * a * c;
if (d == 0) {
x1 = -b / (2 * a);
Console.WriteLine("The only solution is x={0}.", x1);
Console.ReadLine();
}
// If d < 0, no real solutions exist
else if (d < 0) {
Console.WriteLine("There are no real solutions");
Console.ReadLine();
}
// If d > 0, there are two real solutions
else {
x1 = (-b - Math.Sqrt(d)) / (2 * a);
x2 = (-b + Math.Sqrt(d)) / (2 * a);
Console.WriteLine("x1={0} and x2={1}.", x1, x2);
Console.ReadLine();
}
}
}
}
Awesome. Now would be a great time to not get into bad habits:
Problems abound. First off, use
int.TryParse, rather than putting a try-catch around something that can fail.Second, the comment does not match the action of the code. The code determines if the result is an integer; the comment says that it checks for zero.
Third, do not use a goto when what you are attempting to represent is a loop.
Fourth, look at all that duplicated code! You have the same code repeated three times with minor variations.
Make yourself a helper method:
And now your mainline is:
Your bug though is here:
You do the arithmetic in integers, and then convert to doubles. That is, you do the division, round to the nearest integer, and then convert to double. Do it in doubles (or, less likely, in decimals) from the start. It should be:
That is, a, b, and c should not ever be integers.