求一元二次方程的解

findRoot.h

 

#if !defined(FINDROOT_H)
#define FINDROOT_H

#include <iostream>
#include <cmath>
using namespace std;

class findRoot  
{
private:
	float a,b,c,d;
	double x1,x2;
public:
	findRoot(float x, float y, float z);
	~findRoot();
	void display();
protected:
	int flag();
	void one();
	void two();
	void two_c();
};

#endif

findRoot.cpp

 

#include "findRoot.h"

findRoot::findRoot(float x, float y, float z)
{
	a=x;
	b=y;
	c=z;
}

findRoot::~findRoot()
{

}

int findRoot::flag()
{
	if(a==0)
		return -1;
	d=(b*b)-(4*a*c);
	if(d<0)
		two_c();
	else if(d==0)
		one();
	else if(d>0)
		two();
	return 0;
}

void findRoot::display()
{
	if(flag() == -1)
	{
		cout<<"Input error ..."<<endl;
		return;
	}
	cout<<"x1= "<<x1<<" x2= "<<x2<<endl;
	cout<<endl;
}

void findRoot::one()
{
	x1=x2=(-b)/(2*a);
}

void findRoot::two()
{
	x1=(-b+sqrt(d))/(2*a);
	x2=(-b-sqrt(d))/(2*a);
}

void findRoot::two_c()
{
	x1=(-b)/(2*a);
	x2=sqrt(-d)/(2*a);
}

 主函数main.cpp

 

#include "findRoot.h"

void read(float &a, float &b, float &c)
{
	cout<<"Input a :";
	cin>>a;
	cout<<"Input b :";
	cin>>b;
	cout<<"Input c :";
	cin>>c;
}

void main()
{
	float a,b,c;
	cout<<"Get root of ax2+bx+c=0."<<endl;
	for(;;)
	{
		read(a, b, c);
		findRoot obj(a, b, c);
		obj.display();
	}
}

转载于:https://my.oschina.net/showcolors/blog/74648

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值