Test question algorithm to improve programming to find the roots of a quadratic equation (C++)

Resource limitation
Time limitation: 1.0s Memory limitation: 256.0MB
Problem description
  Write a program to solve the real roots of a quadratic equation in one unknown , and the coefficients of the equation are
entered by the user in the xh input format.
  One row and three integers are three of the one-dimensional quadratic equation.   Two coefficients, separated by spaces between the data.
Output format
   output a real number root of the equation (if the two are different, the first two are separated by spaces. If the two are the same, the output will be NO if there is no root)

Sample input
1 -5 4
Sample output
4 1

Sample input
1 -2 1
Sample output
1

Sample input
1 0 1
Sample output
NO

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    
    
	int a ,b ,c ;
	double d , x1 ,x2 ;
	scanf("%d%d%d",&a,&b,&c);
	if(b*b-4*a*c<0){
    
    
		printf("NO\n");
	} else if(b*b-4*a*c==0){
    
    
		x1 = 1.0*(-b)/(2*a);
		printf("%.0f\n",x1);
	}else{
    
    
		d = sqrt(b*b-4*a*c);
		x1 = (-b+d)/(2*a);
		x2 = (-b-d)/(2*a);
		if(x1<x2){
    
    
			int temp = x1;
			x1 = x2;
			x2 = temp;
		}
		printf("%g %g\n",x1,x2);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_51430516/article/details/115361331