一元二次方程与一元二次函数
本帖最后由 My_A 于 2019-3-30 01:03 编辑做了个计算 一元二次方程和一元二次函数顶点与顶点式 的程序,希望大家多多指教
#include <stdio.h>
#include <math.h>
#define NOT_ZERO(x) if((x)==0.0){return 0;} // 二次方程的二次项系数不为0
#define SQUARE(x) ((x)*(x))
#define ANSWER(a,b,c,x) ((a)*SQUARE(x) + (b)*(x) + (c)) // 算方程结果
#define MAX_Y(a,b) ((-(b))/(2*(a))) // 算最大/最小值
typedefstruct{ double x,y; } POINT,*pPOINT;
typedef struct{ double x1,x2; } ANSWER_X,*pANSWER_X;
typedef struct{ double a,h,k; } VERTEX_TYPE,*pVERTEX_TYPE;
// 解方程
int solute(double a,double b,double c,pANSWER_X answer)
{
NOT_ZERO(a);
double delta = SQUARE(b)-(4*a*c);
// 判断根的情况
if(delta >= 0.0){
if(delta > 0){
answer->x1 = (-b+sqrt(delta))/(2*a);
answer->x2 = (-b-sqrt(delta))/(2*a);
}else {
answer->x1 = answer->x2 = MAX_Y(a,b);
}
return 1;
}else{
return 0; // 无实数根
}
}
// 计算顶点坐标
int vertex(double a,double b,double c,pPOINT answer)
{
NOT_ZERO(a);
answer->x = MAX_Y(a,b);
answer->y = ANSWER(a,b,c,answer->x);
return 1;
}
// 计算顶点式
int vertex_type(double a,double b,double c,pVERTEX_TYPE ver){
NOT_ZERO(a);
double a1,h1,k1;
POINT p1;
vertex(a,b,c,&p1);
h1 = p1.x;
k1 = ANSWER(a,b,c,h1);
a1 = (ANSWER(a,b,c,0) - k1)/(SQUARE(h1));
ver->a = a1;
ver->k = k1;
ver->h = h1;
return 1;
}
int main()
{
// 输入一元二次方程的一般式系数
double a=1;
double b=-4;
double c=3;
ANSWER_X answer;
POINT point;
VERTEX_TYPE ver;
if(solute(a,b,c,&answer)){
printf("The quadratic answer is :\n");
printf("\tx1 = %.3lf\n\tx2 = %.3lf\n",answer.x1,answer.x2);
}
if(vertex(a,b,c,&point)){
printf("The vertex-point is :\n");
printf("\t( %.3lf , %.3lf )\n",point.x,point.y);
}
if(vertex_type(a,b,c,&ver)){
printf("The vertex-type is :\n");
printf("\ty = %.3lf * (x - (%.3lf))^2 + (%.3lf)\n",ver.a,ver.h,ver.k);
}
return 0;
}
页:
[1]