ページ 1 / 1
【数学】二次方程式の判別
Posted: 2011年12月31日(土) 13:21
by Cr
コード:
#include <iostream>
using namespace std;
int main(){
double a,b,c;
double answer;
cout << "ax^2+bx+c=0のa,b,cを入力" << endl;
cout << "a=";
cin >> a;
cout << "b=";
cin >> b;
cout << "c=";
cin >> c;
answer = b*b - 4 * a * c;
if(answer==0){
cout << "実数の重解" <<endl;
}else if(answer>0){
cout << "異なる二つの実数解" <<endl;
}else{
cout << "異なる二つの虚数解" <<endl;
}
return 0;
}
Re: 【数学】二次方程式の判別
Posted: 2012年1月01日(日) 21:18
by みけCAT
aが0のときにもきちんと対応しましょう。
Re: 【数学】二次方程式の判別
Posted: 2012年1月03日(火) 18:09
by Cr
一次方程式の場合っすか…
考えてなかったorz
コード:
#include <iostream>
using namespace std;
int main(){
double a,b,c;
double answer;
cout << "ax^2+bx+c=0のa,b,cを入力" << endl;
cout << "a=";
cin >> a;
cout << "b=";
cin >> b;
cout << "c=";
cin >> c;
if(a==0){
cout << "1つの実数解"<<endl;
return 0;
}
answer = b*b - 4 * a * c;
if(answer==0){
cout << "実数の重解" <<endl;
}else if(answer>0){
cout << "異なる二つの実数解" <<endl;
}else{
cout << "異なる二つの虚数解" <<endl;
}
return 0;
}
それともこっちの方がいいかな?
コード:
#include <iostream>
using namespace std;
int main(){
double a,b,c;
double answer;
do{
cout << "ax^2+bx+c=0のa,b,cを入力 (ただしa≠0)" << endl;
cout << "a=";
cin >> a;
cout << "b=";
cin >> b;
cout << "c=";
cin >> c;
if(a==0) cout <<endl<<"入力値が不正です"<<endl<<endl;
}while(!a);
answer = b*b - 4 * a * c;
if(answer==0){
cout << "実数の重解" <<endl;
}else if(answer>0){
cout << "異なる二つの実数解" <<endl;
}else{
cout << "異なる二つの虚数解" <<endl;
}
return 0;
}
一つ目だとa=b=c=0のときとか、またいろいろ必要になってくるし…