求助
求一元二次方程 ax2+bx+c=0 的解。解有以下几种可能:①系数a=0时,该方程不是二次方程。
②判别式b2-4ac=0时,有两个相等实根。
③判别式b2-4ac>0时,有两个不等实根。
④判别式b2-4ac<0时,有两个共轭复根。
要求:
①输入为:-0.00000001, 1, 0.6
输出为:该方程不是2次方程!
②输入为:1, 2, 1
输出为:该方程有两个相等实根:
x1=x2=-1.00
③输入为:1, 3, 1
输出为:该方程有两个不相等实根:
x1=-0.38
x2=-2.62
④输入为:1, 3, 4
输出为:该方程有两个共轭复根:
x1=-1.50+1.32 i
x2=-1.50-1.32 i
VPL
有没有大佬会做啊 救救孩子吧
是什么语言? 本帖最后由 傻眼貓咪 于 2022-3-25 19:42 编辑
C++#include <iostream>
#include <complex>
#include <cmath>
#include <utility>
#include <complex>
#include <iomanip>
auto discriminant = [](double a, double b, double c) -> double { return b * b - 4 * a * c; };
auto roots = [](double a, double b, double c) -> std::pair<double, double> { return std::make_pair((- b + sqrt(discriminant(a, b, c))) / (2 * a), (- b - sqrt(discriminant(a, b, c))) / (2 * a)); };
auto rootsImag = [](double a, double b, double c) -> std::pair<std::complex<double>, std::complex<double>> { return std::make_pair((- b + sqrt(std::complex<double>(discriminant(a, b, c)))) / (2 * a), (- b - sqrt(std::complex<double>(discriminant(a, b, c)))) / (2 * a)); };
auto isINT = [](double num) -> bool { return !(num - static_cast<int> (num)); };
int main()
{
double a, b, c;
std::cin >> a >> b >> c;
if(fabs(a) - 0 <= 1e-8){
std::cout << "该方程不是2次方程!" << std::endl;
}
else if(!(discriminant(a, b, c))){
std::pair<double, double> R = roots(a, b, c);
if(!isINT(R.first))
std::cout
<< std::fixed << std::setprecision(2);
std::cout
<< "该方程有两个相等实根:"
<< std::endl
<< "x1 = x2 = "
<< R.first
<< std::endl;
}
else if(discriminant(a, b, c) > 0){
std::pair<double, double> R = roots(a, b, c);
if(!isINT(R.first) && !isINT(R.second))
std::cout
<< std::fixed << std::setprecision(2);
std::cout
<< "该方程有两个不相等实根:" << std::endl
<< "x1 = " << R.first << std::endl
<< "x2 = " << R.second << std::endl;
}
else{
std::pair<std::complex<double>, std::complex<double>> R = rootsImag(a, b, c);
std::cout
<< "该方程有两个共轭复根:" << std::endl
<< "x1 = " << std::fixed << std::setprecision(2) << real(R.first) << "+" << imag(R.first) << "i" << std::endl
<< "x2 = " << std::fixed << std::setprecision(2) << real(R.second) << imag(R.second) << "i" << std::endl;
}
return 0;
}
页:
[1]