題目:
求一元二次方程式 ax2+bx+c=0 的根
每組輸入共一行,內含三個整數 a, b, c 以空白隔開。
<aside> 💡
照題目意思來,主要用if_else
</aside>
a,b,c = map(int, input().split(' ')) # 拆分輸入的字串,轉換成數字提供給變數 a、b、c
if a !=0: # 如果 a 不等於 0
r = b**2 - 4*a*c # 計算開根號內的數值
if r>0: # 如果開根號內的數值大於 0
x1 = int((b*-1 + r**0.5)/(2*a)) # 套用公式求出 x1
x2 = int((b*-1 - r**0.5)/(2*a)) # 套用公式求出 x2
if x1>x2: # 根據題目輸出結果
print(f'Two different roots x1={x1} , x2={x2}')
else:
print(f'Two different roots x1={x2} , x2={x1}')
elif r == 0:
x = int((b*-1 + r**0.5)/(2*a))
print(f'Two same roots x={x}') # 根據題目輸出結果
else: # 如果開根號內的數值小於 0
print('No real root')
else: # 如果 a 等於 0
print('No real root')
#include <bits/stdc++.h>
using namespace std;
int main() {
int a,b,c,r;double x1,x2,x;
cin>>a>>b>>c;
if (a!=0){
r=b*b - 4*a*c;
if(r>0){
x1=(b*-1 + sqrt(r))/(2*a);
x2=(b*-1 - sqrt(r))/(2*a);
if(x1>x2)
cout<<"Two different roots x1="<<x1<<" , x2="<<x2;
else
cout<<"Two different roots x1="<<x2<<" , x2="<<x1;
}
else if(r==0){
x=(b*-1 + sqrt(r))/(2*a);
cout<<"Two same roots x="<<x;
}
else
cout<<"No real root";
}
else
cout<<"No real root";
return 0;
}