|
发表于 2022-3-25 19:37:17
|
显示全部楼层
本帖最后由 傻眼貓咪 于 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;
- }
复制代码 |
|