C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ 求二次方程所有根的程序

求二次方程所有根的C++程序

该程序接受来自用户的二次方程的系数并显示根(实根和复根取决于判别式)。
要理解此示例,您应该了解以下C++ 编程 主题:
C++ if, if...else 和嵌套 if...else
对于二次方程 ax2+bx+c = 0(其中 a、b 和 c 是系数),其根由以下公式给出。
b2-4ac 被称为二次方程的判别式。判别式说明根的性质。
如果判别式大于 0,则根为实数且不同。 如果判别式等于 0,则根为实数且相等。 如果判别式小于 0,则根复杂且不同。

示例: 二次方程的根

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;
    discriminant = b*b-4*a*c;
    
    if (discriminant > 0) {
        x1 = (-b + sqrt(discriminant)) / (2*a);
        x2 = (-b-sqrt(discriminant)) / (2*a);
        cout << "Roots are real and different." << endl;
        cout << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }
    
    else if (discriminant == 0) {
        cout << "Roots are real and same." << endl;
        x1 =-b/(2*a);
        cout << "x1 = x2 =" << x1 << endl;
    }
    else {
        realPart =-b/(2*a);
        imaginaryPart =sqrt(-discriminant)/(2*a);
        cout << "Roots are complex and different."  << endl;
        cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
        cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
    }
    return 0;
}
输出
Enter coefficients a, b and c: 4
5
1
Roots are real and different.
x1 =-0.25
x2 =-1
在这个程序中, sqrt() 库函数用于求一个数的平方根。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4