#5245: 為什麼會錯


pentiumone (TK)


#include <iostream>
#include <math.h>
using namespace std;
int main()
{
    double a, b, c, ans_1, ans_2;
    while(cin >> a >> b >> c)
    {
        ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/2*a;
        ans_2 =(-b-sqrt(pow(b, 2)-(4*a*c)))/2*a;
        if(pow(b, 2)-(4*a*c)<0)
            cout << "No real root" << endl;    
        else if(ans_1 == ans_2)
            cout << "Two same roots x=" << ans_1 << endl;
        else
            cout << "Two different roots x1=" << ans_1 << " , x2=" << ans_2 << endl;
    }
    return 0;
}

程式碼如上

我在自己電腦試都沒問題  可是第5個測資一直說我答案錯了 

可以幫我看一下嗎?

#5263: Re:為什麼會錯


pentiumone (TK)


#include
#include
using namespace std;
int main()
{
    double a, b, c, ans_1, ans_2;
    while(cin >> a >> b >> c)
    {
        ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/2*a;
        ans_2 =(-b-sqrt(pow(b, 2)-(4*a*c)))/2*a;
        if(pow(b, 2)-(4*a*c)<0)
            cout << "No real root" << endl;    
        else if(ans_1 == ans_2)
            cout << "Two same roots x=" << ans_1 << endl;
        else
            cout << "Two different roots x1=" << ans_1 << " , x2=" << ans_2 << endl;
    }
    return 0;
}

程式碼如上

我在自己電腦試都沒問題  可是第5個測資一直說我答案錯了 

可以幫我看一下嗎?

0.0
#5265: Re:為什麼會錯


abcd6891 (曄哥)


#include
#include
using namespace std;
int main()
{
    double a, b, c, ans_1, ans_2;
    while(cin >> a >> b >> c)
    {
        ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/2*a;
        ans_2 =(-b-sqrt(pow(b, 2)-(4*a*c)))/2*a;
        if(pow(b, 2)-(4*a*c)<0)
            cout << "No real root" << endl;    
        else if(ans_1 == ans_2)
            cout << "Two same roots x=" << ans_1 << endl;
        else
            cout << "Two different roots x1=" << ans_1 << " , x2=" << ans_2 << endl;
    }
    return 0;
}

程式碼如上

我在自己電腦試都沒問題  可是第5個測資一直說我答案錯了 

可以幫我看一下嗎?

0.0

ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/2*a;

ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/2*a;

改成

 

ans_1 =(-b+sqrt(pow(b, 2)-(4*a*c)))/(2*a);

 

運算子優先順序問題 

因為如果a不是1,會出錯