1. 程式人生 > >習題 14.1 求一元二次方程式ax^2+bx+c=0的實根,如果方程沒有實根,則輸出有關警告資訊。

習題 14.1 求一元二次方程式ax^2+bx+c=0的實根,如果方程沒有實根,則輸出有關警告資訊。

C++程式設計(第三版) 譚浩強 習題14.1 個人設計

習題 14.1 求一元二次方程式 a x 2 + b x +
c = 0 ax^2+bx+c=0
的實根,如果方程沒有實根,則輸出有關警告資訊。

程式碼塊:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double a, b, c, disc;
	cout<<"Please enter a, b, c: ";
	cin>>a>>b>>c;
	disc=b*b-4*a*c;
	try
	{
		if (disc==0)
			cout<<"x="<<(-1)*b/(2*a)<<endl;
		else if (disc>0)
			cout<<"x1="<<((-1)*b+sqrt(disc))/(2*a)<<", x2="<<((-1)*b-sqrt(disc))/(2*a)<<endl;
		else if (disc<0) throw a;
	}
	catch(double){
		cout<<"Error! No result!"<<endl;
	}
	system("pause");
	return 0;
}