#11830: c++參考ans


shuo19971203 (shuo)

學校 : 義守大學
編號 : 62158
來源 : [120.118.4.117]
最後登入時間 :
2020-01-08 15:41:19
a006. 一元二次方程式 | From: [36.238.39.158] | 發表日期 : 2017-03-20 20:14

//求一元二次方程式ax^2+bx+c=0;
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
int a = 0, b = 0, c = 0;
double ans1 = 0, ans2 = 0;

while (cin >> a >> b >> c)
{
ans1 = (-b + sqrt((b*b) - (4 * a*c))) / (2 * a);
ans2 = (-b - sqrt((b*b) - (4 * a*c))) / (2 * a);

if (b*b - 4 * a*c < 0)
{
cout << "No real root" << endl;
}
else // b^2-4ac>=0
{
if (ans1 != ans2 && ans1 > ans2)
{
cout << "Two different roots x1=" << ans1 << " , x2=" << ans2 << endl;
}
else if (ans1 != ans2 && ans2 > ans1)
{
cout << "Two different roots x1=" << ans2 << " , x2=" << ans1 << endl;
}
else if (ans1 == ans2)
{
cout << "Two same roots x=" << ans1 << endl;
}
}
}
system("PAUSE");
return 0;
}

 
#11858: Re:c++參考ans


nkavengertree (LaG)

學校 : 不指定學校
編號 : 62501
來源 : [49.216.191.28]
最後登入時間 :
2021-11-21 03:06:49
a006. 一元二次方程式 | From: [118.168.227.231] | 發表日期 : 2017-03-31 22:49

//求一元二次方程式ax^2+bx+c=0;
#include
#include
using namespace std;

int main()
{
int a = 0, b = 0, c = 0;
double ans1 = 0, ans2 = 0;

while (cin >> a >> b >> c)
{
ans1 = (-b + sqrt((b*b) - (4 * a*c))) / (2 * a);
ans2 = (-b - sqrt((b*b) - (4 * a*c))) / (2 * a);

if (b*b - 4 * a*c < 0)
{
cout << "No real root" << endl;
}
else // b^2-4ac>=0
{
if (ans1 != ans2 && ans1 > ans2)
{
cout << "Two different roots x1=" << ans1 << " , x2=" << ans2 << endl;
}
else if (ans1 != ans2 && ans2 > ans1)
{
cout << "Two different roots x1=" << ans2 << " , x2=" << ans1 << endl;
}
else if (ans1 == ans2)
{
cout << "Two same roots x=" << ans1 << endl;
}
}
}
system("PAUSE");
return 0;
}

 sqrt( (b*b) - (4 * a*c) )
若是小於0,應該會變成複數的感覺,雖然應該不太會影響答案,只是覺得不太好

#include <iostream>

#include <cmath>

using namespace std;

int main()

{

    int a,b,c;

    while(cin>>a>>b>>c){

 

        int cal = b*b-4*a*c;

        if (cal < 0){

            cout << "No real root\n";

        }

        else if (cal == 0){

            cout << "Two same roots x=" << (-1)*b/(2*a) << endl;

        }

        else{

            cout << "Two different roots x1=" << ((-1)*b+sqrt(cal))/(2*a);

            cout << " , x2=" << ((-1)*b-sqrt(cal))/(2*a) << endl;

        }

    }

return 0;

}

 

 

 
ZeroJudge Forum