hey absolute beginner in c#. tried make simple maths question asks multiplication. used "double" variable , when answer in less than/equals 1 decimal says answer correct when answer more 1 decimal wrong if correct how 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 " + 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 practice more!"); console.writeline ("<<press space terminate>>"); console.readkey (); } } } }
the problem due rounding errors.
it's not possible accurately represent floating point numbers type double
- one's 1.1 or 2.3. means when multiply them 1.2099999 (for example) rather 1.21.
you're doing equality test user's answer (1.21) against calculated value , fail.
if switch using type decimal
these problems should solve - @ least small numbers using here.
the other solution test difference between 2 numbers less small amount (0.000001 example):
if (math.abs(answer - n1 * n2) < 0.000001) { console.writeline ("well done!"); console.readkey (); }
Comments
Post a Comment