Что не так с этим кодом C ++? - PullRequest
0 голосов
/ 15 ноября 2010

Я сделал несколько изменений здесь, но я все еще не получаю то, что ожидаю получить. Например, когда я заменяю a на 1, b на 2, а c на 2, я должен получить -1 + i и -1-i, но когда я запускаю код, он дает мне -0.73205 + i и - 2.73205 + i. Как мне это исправить?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
    double a, b, c, disc, x1, x2, root1, root2, imrt1, imrt2;
    char i;
    cout<<"Enter a, b and c ";
    cin >> a >> b >> c ;


    if(disc == 0.0 && b == 0.0)
        cout<<"The equation is degenerate and has no real roots. \n";
    else if(a == 0.0)
        cout<<"The equation has one real root x = "<< -c/b <<endl;

    else
    {
        disc =  pow(b,2.0)-4*a*c;
        if (disc > 0.0)
        {
            disc = sqrt(disc);
            root1 = (-b+disc)/(2*a);
            root2 = (-b-disc)/(2*a);
            cout<<"The two real roots are "<<root1<<" and "<<root2<<endl;
        }

        else if(disc < 0.0)
        disc =  pow(b,2.0)+4*a*c;
        disc = sqrt(disc);
        imrt1 = (-b+disc)/(2*a);
        imrt2 = (-b-disc)/(2*a);
        cout<<"The two imaginary roots are "<<imrt1<<"+i"<<" and <<imrt2<<"+i"<<"\n";

        else
            cout<<"Both roots are equal to "<<-b/(2*a)<<endl;
    }//End of compound statement for the outer else

    system("PAUSE");
    return 0;
}

Ответы [ 3 ]

4 голосов
/ 15 ноября 2010

Вы пропустили фигурные скобки из else, если (disc <0.0), следовательно, следующий else потерян

0 голосов
/ 15 ноября 2010
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main(){
    double a, b, c, disc, x1, x2, root1, root2, imrt1, imrt2, disc2;
    char i;
    cout<<"Enter a, b and c ";
    cin >> a >> b >> c ;


    if(disc == 0.0 && b == 0.0)
        cout<<"The equation is degenerate and has no real roots. \n";
    else if(a == 0.0)
        cout<<"The equation has one real root x = "<< -c/b <<endl;

    else
    {
        disc =  pow(b,2.0)-4*a*c;
        if (disc > 0.0)
        {
            disc = sqrt(disc);
            root1 = (-b+disc)/(2*a);
            root2 = (-b-disc)/(2*a);
            cout<<"The two real roots are "<<root1<<" and "<<root2<<endl;
        }

        else if(disc < 0.0)
            disc2 =  pow(b,2.0)-4*a*c;
        disc2 = sqrt(disc2);
        imrt1 = (-b+disc2)/(2*a);
        imrt2 = (-b-disc2)/(2*a);
        cout<<"The two imaginary roots are "<<"i"<<imrt1<<" and "<<"i"<<imrt2<<"\n";

        else
            cout<<"Both roots are equal to "<<-b/(2*a)<<endl;
    }//End of compound statement for the outer else

    system("PAUSE");
    return 0;
}

вот ваш код с отступом (30 секунд под блокнотом ++)

и становится очевидным (опубликовано vinothkr), что вы пропустили скобки

иначе, если (диск <0.0) </p>

Также Диск в первом тесте не инициализируется ...

И я бы также рекомендовал всегда использовать {} с if else. Даже если это сэкономит 5 секунд, чтобы не записать его, вы потеряете 1 / 2h отладки любых изменений.

для сравнения

int main(){
double a, b, c, disc, x1, x2, root1, root2, imrt1, imrt2, disc2;
char i;
cout<<"Enter a, b and c ";
cin >> a >> b >> c ;

    //Disc never init...
if(disc == 0.0 && b == 0.0){
    cout<<"The equation is degenerate and has no real roots. \n";
}else if(a == 0.0){
    cout<<"The equation has one real root x = "<< -c/b <<endl;

}else{
    disc =  pow(b,2.0)-4*a*c;
    if (disc > 0.0){
        disc = sqrt(disc);
        root1 = (-b+disc)/(2*a);
        root2 = (-b-disc)/(2*a);
        cout<<"The two real roots are "<<root1<<" and "<<root2<<endl;
    }else if(disc < 0.0){
        disc2 =  pow(b,2.0)-4*a*c;
        disc2 = sqrt(disc2);
        imrt1 = (-b+disc2)/(2*a);
        imrt2 = (-b-disc2)/(2*a);
        cout<<"The two imaginary roots are "<<"i"<<imrt1<<" and "<<"i"<<imrt2<<"\n";
    }else{
        cout<<"Both roots are equal to "<<-b/(2*a)<<endl;
    }
}//End of compound statement for the outer else

system("PAUSE");
return 0;

}

0 голосов
/ 15 ноября 2010

При первом тесте для if (disc == 0.0 && b == 0.0) переменная disc неинициализирована и, следовательно, может иметь любое значение. Вы, вероятно, намеревались написать if (a == 0.0 && b == 0.0) ...


Ваша математика в воображаемом случае более чем подозрительна. Если дискриминант отрицателен, то вам нужна действительная часть '-b / 2a', а мнимые части '± √ (b² - 4ac) / 2a'. Итак, может быть, вам нужно:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    double a, b, c;

    cout << "Enter a, b and c: ";
    cin  >> a >> b >> c;

    if (a == 0.0 && b == 0.0)
        cout << "The equation is degenerate and has no real roots.\n";
    else if (a == 0.0)
        cout << "The equation has one real root x = " <<  -c/b  << endl;
    else
    {
        double disc = pow(b,2.0)-4*a*c;
        if (disc > 0.0)
        {
            disc = sqrt(disc);
            double root1 = (-b+disc)/(2*a);
            double root2 = (-b-disc)/(2*a);
            cout << "The two real roots are " << root1 << " and " << root2 << endl;
        }
        else if (disc < 0.0)
        {
            double imag = sqrt(-disc)/(2*a);
            double real = (-b)/(2*a);
            cout << "The two complex roots are "
                 << "(" << real << "+" << imag << "i)" << " and "
                 << "(" << real << "-" << imag << "i)" << endl;
        }
        else
            cout << "Both roots are equal to " << -b/(2*a) << endl;
    }
    return 0;
}

Пример выходных данных:

Enter a, b and c: 2 6 3
The two real roots are -0.633975 and -2.36603

Enter a, b and c: 2 4 3
The two complex roots are (-1+0.707107i) and (-1-0.707107i)

Enter a, b and c: 3 6 3
Both roots are equal to -1
...