Often, statements or a sequence of statements in a statement block must be executed under specific conditions. A classic example is the calculation of the solutions of a quadratic equation in the general form a·x²+b·x+c = 0, which is first transformed into the normal form x²+p·x+q = 0, in order to make the sample according to Vieta easy for the two solutions x1 and x2 with x1+x2 = -p and x1·x2 = q. Afterwards, their solution variety is determined by means of the discriminant D with D = (p²/4-q). One arrives at exactly 3 distinguishable cases:
By using the component gb. complex you can quickly implement the above mentioned approach:
Public Function CalculateRoots(fP As Float, fQ As Float) As Variant[] Dim fDiskriminante As Float = 0 Dim fX1, fX2 As Variant Dim fXC1, fXC2 As Complex fDiskriminante = (fP * fP) / 4 - fQ Select Sgn(fDiskriminante) Case 1 ' D>0 fX1 = - fP / 2 - Sqr(fDiskriminante) fX2 = - fP / 2 + Sqr(fDiskriminante) Return [fX1, fX2] Case 0 ' D=0 fX1 = - fP / 2 fX2 = fX1 Return [fX1, fX2] Case Else ' D<0 fXC1 = Complex(- fP / 2, - Sqr(- fDiskriminante)) fXC2 = fXC1.Conj() Return [fXC1, fXC2] End Select End
This chapter 10.2 describes the following control structures:
Oft müssen Anweisungen oder eine Folge von Anweisungen in einem Anweisungsblock unter ganz bestimmten Bedingungen ausgeführt werden. Ein klassisches Beispiel ist die Berechnung der Lösungen einer quadratischen Gleichung in der allgemeinen Form a·x²+b·x+c = 0. Diese wird zuerst in die Normalform x²+p·x+q = 0 transformiert, um die Probe nach Vieta für die beiden Lösungen x1 und x2 mit x1+x2 = -p und x1·x2 = q einfach zu gestalten. Danach bestimmt man deren Lösungsvielfalt mit Hilfe der Diskriminante D mit D = (p²/4-q). Man kommt auf genau 3 unterscheidbare Fälle:
Mit dem Einsatz der Komponente gb.complex können Sie den o.a. Ansatz schnell realisieren:
Public Function CalculateRoots(fP As Float, fQ As Float) As Variant[] Dim fDiskriminante As Float = 0 Dim fX1, fX2 As Variant Dim fXC1, fXC2 As Complex fDiskriminante = (fP * fP) / 4 - fQ Select Sgn(fDiskriminante) Case 1 ' D>0 fX1 = - fP / 2 - Sqr(fDiskriminante) fX2 = - fP / 2 + Sqr(fDiskriminante) Return [fX1, fX2] Case 0 ' D=0 fX1 = - fP / 2 fX2 = fX1 Return [fX1, fX2] Case Else ' D<0 fXC1 = Complex(- fP / 2, - Sqr(- fDiskriminante)) fXC2 = fXC1.Conj() Return [fXC1, fXC2] End Select End ' CalculateRoots(fP As Float, fQ As Float) As Variant[]
In diesem Kapitel 10.2 werden die folgenden Kontrollstrukturen beschrieben: