C语言求解一元二次方程

94 阅读1分钟

一元二次方程的根

本篇博客关于如何求一元二次方程的根,希望对你有所帮助

代码如下:

#include<stdio.h>
#include<math.h>
int solutioin(double a, double b, double c, double& x1, double& x2) {
	double d;
	d = b * b - 4 * a * c;
	if (d > 0) {
		x1 = (-b + sqrt(d) / (2 * a));
		x2 = (-b - sqrt(d) / (2 * a));
		return 2;
	}
	else if (d == 0) {
		x1 = (-b) / (2 * a);
		return 1;
	}
	else {
		return 0;
	}
}
int main() {
	double a = 2, b = -6, c = 3;
	double x1, x2;
	int s = solutioin(a, b, c, x1, x2);
	if (s == 1)
		printf("一个根:x=%1f\n", x1);
	else if (s == 2)
		printf("两个根:x1=%1f,x2=%1f\n", x1, x2);
	else
		printf("没有根\n");


}