Hey I am a absolute beginner in c#. I tried to make a simple maths question where it asks you about multiplication. I used "double" as variable and when the answer is in less than/equals to one decimal it says the answer is correct but when the answer is more than one decimal it will say you are wrong even if i am correct any help how to resolve this? Thanks
using System;
namespace Mathsquiestion {
class MainClass {
public static void Main (string[] args) {
double n1 = 1.1;
double n2 = 1.1;
double answer;
Console.WriteLine ("what is " + n1 + " times " + n2);
answer = Convert.ToDouble (Console.ReadLine ());
if (answer == n1 * n2) {
Console.WriteLine ("Well done!");
Console.ReadKey ();
}
if (answer != n1 * n2) {
Console.WriteLine ("You have to practice some more!");
Console.WriteLine ("<<Press space to terminate>>");
Console.ReadKey ();
}
}
}
}
The problem is due to rounding errors.
It's not possible to accurately represent all floating point numbers as type double
- even one's like 1.1 or 2.3. This means that when you multiply them together you get 1.2099999 (for example) rather than 1.21.
You're doing an equality test for the user's answer (1.21) against the calculated value and it will fail.
If you switch to using type decimal
these problems should solve themselves - at least for the small numbers you are using here.
The other solution is to test that the difference between the two to numbers is less than some small amount (0.000001 for example):
if (Math.Abs(answer - n1 * n2) < 0.000001)
{
Console.WriteLine ("Well done!");
Console.ReadKey ();
}