Algorithm to improve programming to find the roots of a quadratic equation

问题描述
  编写一个求解一元二次方程的实数根的程序,方程的系数由用户在运行xh
输入格式
  输入一行三个整数分别为一元二次方程的三个系数,数据之间以空格隔开
输出格式
  输出一行为方程的实数根(若两根不同 较大的在前 两根以空格隔开 若两根相同 输出一个 若无根 输出 NO )
样例输入
1 -5 4
样例输出
4 1
样例输入
1 -2 1
样例输出
1
样例输入
1 0 1
样例输出
NO

Problem solution ideas:

Formula method:
Insert picture description here
Insert picture description here
Insert picture description here

code show as below:

#include<stdio.h>
#include<math.h>
int main() {
    
    
	double a,b,c;
	scanf("%lf%lf%lf",&a,&b,&c);
	double root=0,x1=0,x2=0;
	root=b*b-4*a*c;
	if(root>0){
    
    
		x1=(-b+sqrt(root))/(2*a);
		x2=(-b-sqrt(root))/(2*a);
		if(x1>x2){
    
    
			printf("%g %g",x1,x2);
		}
	}else if(root==0){
    
    
		x1=(-b)/(2*a);
		x2=x1; 
		printf("%g",x1);
	}else{
    
    
		printf("NO");
	}
	
	return 0;
}

Insert picture description here

This question should pay attention to a precision output, otherwise it will be sad for some data. For example, 2 5 1.

printf("%g %g",x1,x2);

What does %g mean in this line of code.
%g is an output format type of the C language printf() function. It indicates that single and double-precision real numbers are output with the shorter output width in %f%e. The %e format is used when the exponent is less than -4 or greater than or equal to the precision.

for example

printf("%g\n", 0.00001234);

printf("%g\n", 0.0001234);

printf("%.2g\n", 123.45);

printf("%.2g\n", 23.45);

result:

1.234e-05
0.0001234
1.2e+02
23

Guess you like

Origin blog.csdn.net/mjh1667002013/article/details/115037588