Quadratische Gleichung mit complex<double> lösen
-
Huhu
,
da man an einem Samstag ja nichts besseres zu tun hat, schickt mein Informatiklehrer uns Schülern am Freitag um c.a 22:00 Uhr eine e-mail, betitelt mit dem wunderbaren Wort "Hausaufgaben"..Ich wurde der Gruppe C++ zugeteilt und darf nun folgende Aufgabe lösen:
Schreiben Sie ein Programm zur Lösung der quadratischen Gleichung
x^2 + px + q = 0, wobei Sie komplexe Zahlen für das Ergebnis verwenden.Zugegeben, ich hab mehr geschafft als ich mir zugetraut habe, das Ergebnis stimmt aber trotzdem nicht.

#include <iostream> #include <complex> #include <cmath> using namespace std; int main( void ) { double p, q; cout << "Bitte die Koeffizienten p und q eingeben: "; /* Bezogen auf die Darstellung x * x + p * x + q = 0 */ cin >> p >> q; double Diskriminante = pow( p, 2 ) / 4.0 - q; if ( Diskriminante >= 0.0 ) { double x1 = -p / 2.0 + sqrt( Diskriminante ); double x2 = -p / 2.0 + sqrt( Diskriminante ); cout << "x1= " << x1 << endl; cout << "x2= " << x2 << endl; } else { complex<double> result( -p / 2, sqrt( Diskriminante ) ); cout << "x1= " << result << endl; cout << "x2= " << conj( result ) << endl; }Wäre wirklich super, wenn der ein oder andere da mal drüber schaut und mir ggf. den Fehler meldet
.
-
Die Diskriminante ist ein double.
Im else Teil, wo sie negativ ist, rufst du std::sqrt auf. Die Überladung für double kommt aber nicht mit negativen Zahlen klar.
Du musst sie also mit der positiven Diskrimante aufrufen, dann hast du auch den richtigen Imaginärteil.
-
Danke!

-
Vorschlag:
double p, q; std::cin >> p >> q; std::complex<double> Diskriminante = p*p - 4*q; std::complex<double> fix = -p/2, pm = std::sqrt(Diskriminante)/2.; std::cout << "x1= " << fix+pm << '\n' << "x2= " << fix-pm << '\n';