Friday, July 13, 2012

Solve quadratic equations x² + bx+c = 0

This week I wrote a Math program to present the user with 10 quadratic equations in the format
 x² + bx + c = 0 and asked the user to input the roots of the equation (solutions for x)

I will pick two random integer roots between -10 and 10 and work out the equation from there so that I make sure that the equation will have two integer roots and the user does not have to enter real numbers or deal with quadratic equations with no real roots.

Since the coefficient of x² is 1, b is -1*(sum of the roots) and c is the product of the roots:
b = -(x1+x2)
c =  x1*x2

My program picks two values for x between -10 and 10 and then calculates b and c to display the question.  The question could include x² + 0x -16 = 0 and x² + 5x + 0 = 0 since x1 and x2 could be the additive inverse of each other (same number different sign) or one or both roots could be 0.

My interface looks like this:

The code to ask 10 questions look like this:

Note :

  • you have to add a + in front of positive values before you join the values for the expression.
  • The reason why I multiplied the answers the user enters by one, is to remove any extra spaces and + symbols that the user might enter.  Scratch converts the user input + 8 to 8 when you multiply + 8 with 1 :-)
  • You have to allow the user to input the roots in any order, hence the composite condition to check the answers 

1 comment:

  1. A quadratic equation with real or complex coefficients has two solutions, called roots. These two solutions may or may not be distinct, and they may or may not be real.quadratic equations