①用普通算法解决(摘抄自网上):
#include <iostream>
#include <cmath>
using namespace std;
void main()
{
int a,b,c;
float x1,x2,z;
cin>>a>>b>>c;
z=b*b-4*a*c;
if(z>0)
{
x1=((-b)+sqrt(z))/(2*a);
x2=((-b)-sqrt(z))/(2*a);
cout<<"The result: x1="<<x1<<" x2="<<x2<<endl;
}
else
if(z==0)
{
x1=-b/(2*a);
cout<<"The result: x1="<<x1<<endl;
}
else
cout<<"no result";
}
②用函数解决(自己编的):
#include <iostream.h>
#include <math.h>
int yan(int a,int b,int c)
{
if(b*b-4*a*c>=0)
return 1;
else return 0;
}
int root1(int a,int b,int c)
{
double i;
i=((-b)+sqrt(b*b-4*a*c))/(2*a);
return i;
}
int root2(int a,int b,int c)
{
double i;
i=((-b)-sqrt(b*b-4*a*c))/(2*a);
return i;
}
void main()
{
int a,b,c;
cin>>a>>b>>c;
if(yan(a,b,c))
{
cout<<"x1="<<root1(a,b,c)<<endl;
cout<<"x2="<<root2(a,b,c)<<endl;
}
else
cout<<“没值"<<endl;
}