2016-03: Math 1
Write a program to solve quadratic equations.
Risolvere un’equazione di secondo grado ax2+bx+c=0, dati i coefficienti a, b e c.
Un po’ di matematica…

Esempi
| Istanza | Elaborazione | Risposta | |||
| 1 | x2-5x+6=0 | a=1 b=-5 c=6 |
D=b2-4ac=… D=1>0 |
x1=… x2=… |
2 3 |
|---|---|---|---|---|---|
| 2 | x2+2x+1=0 | a=1 b=2 c=1 |
D=b2-4ac=… D=0 |
x1,2=-2/2 | -1 |
| 3 | x2+x+1=0 | a=1 b=1 c=1 |
D=b2-4ac=… D=-3<0 |
… | Impossibile |
Il codice corrispondente
TextWindow.WriteLine("EQUAZIONE DI SECONDO GRADO")
TextWindow.WriteLine("--------------------------------------------")
TextWindow.Write("A = ")
a=TextWindow.ReadNumber()
TextWindow.Write("B = ")
b=TextWindow.ReadNumber()
TextWindow.Write("C = ")
c=TextWindow.ReadNumber()
TextWindow.WriteLine("--------------------------------------------")
delta=b*b-4*a*c
TextWindow.WriteLine("DELTA = " + delta)
TextWindow.WriteLine("--------------------------------------------")
If(delta > 0) Then
TextWindow.WriteLine("DELTA positivo: due soluzioni.")
x1=(-b-Math.SquareRoot(delta))/(2*a)
x2=(-b+Math.SquareRoot(delta))/(2*a)
TextWindow.WriteLine("X1 = " + x1)
TextWindow.WriteLine("X2 = " + x2)
Else
If(delta = 0) then
TextWindow.WriteLine("DELTA nullo: una soluzione.")
x=-b/(2*a)
TextWindow.WriteLine("X = " + x)
Else
TextWindow.WriteLine("DELTA negativo: nessuna soluzione reale.")
EndIf
EndIf
TextWindow.WriteLine("--------------------------------------------")
Se il caso a=0 non viene gestito adeguatamente si incorre in una divisione per zero!

TextWindow.WriteLine("EQUAZIONE DI SECONDO GRADO")
TextWindow.WriteLine("--------------------------------------------")
TextWindow.Write("A = ")
a=TextWindow.ReadNumber()
TextWindow.Write("B = ")
b=TextWindow.ReadNumber()
TextWindow.Write("C = ")
c=TextWindow.ReadNumber()
TextWindow.WriteLine("--------------------------------------------")
If(a = 0) Then
TextWindow.WriteLine("a=0, è un'equazione di primo grado...")
Else
delta=b*b-4*a*c
TextWindow.WriteLine("DELTA = " + delta)
TextWindow.WriteLine("--------------------------------------------")
If(delta > 0) Then
TextWindow.WriteLine("DELTA positivo: due soluzioni.")
x1=(-b-Math.SquareRoot(delta))/(2*a)
x2=(-b+Math.SquareRoot(delta))/(2*a)
TextWindow.WriteLine("X1 = " + x1)
TextWindow.WriteLine("X2 = " + x2)
Else
If(delta = 0) then
TextWindow.WriteLine("DELTA nullo: una soluzione.")
x=-b/(2*a)
TextWindow.WriteLine("X = " + x)
Else
TextWindow.WriteLine("DELTA negativo: nessuna soluzione reale.")
EndIf
EndIf
EndIf
TextWindow.WriteLine("--------------------------------------------")