21xrx.com
2024-09-20 06:39:24 Friday
登录
文章检索 我的文章 写文章
C++编写一元二次方程求根的代码
2023-07-10 03:53:23 深夜i     --     --
C++ 一元二次方程 求根 代码

一元二次方程是高中数学中比较基础的知识点,也是数学模型及工程应用中较为常见的数学工具,解法有多种,其中一种就是求根公式。

一元二次方程的一般形式为:ax² + bx + c = 0。求根公式为:x = [-b ± sqrt(b² - 4ac)] / 2a。

下面我们来看一下如何用C++编写一元二次方程求根的代码。

代码如下:


#include <iostream>

#include <cmath>

using namespace std;

int main() {

  double a, b, c, root1, root2, discriminant, realPart, imagPart;

  cout << "Enter coefficients a, b and c: ";

  cin >> a >> b >> c;

  // calculate discriminant

  discriminant = b * b - 4 * a * c;

  // condition for real and different roots

  if (discriminant > 0) {

    root1 = (-b + sqrt(discriminant)) / (2 * a);

    root2 = (-b - sqrt(discriminant)) / (2 * a);

    cout << "Roots are real and different." << endl;

    cout << "Root 1 = " << root1 << endl;

    cout << "Root 2 = " << root2 << endl;

  }

  // condition for real and equal roots

  else if (discriminant == 0) {

    cout << "Roots are real and same." << endl;

    root1 = (-b + sqrt(discriminant)) / (2 * a);

    cout << "Roots is: " << root1 << endl;

  }

  // if roots are not real

  else {

    realPart = -b / (2 * a);

    imagPart = sqrt(-discriminant) / (2 * a);

    cout << "Roots are complex and different." << endl;

    cout << "Root 1 = " << realPart << " + " << imagPart << "i" << endl;

    cout << "Root 2 = " << realPart << " - " << imagPart << "i" << endl;

  }

  return 0;

}

代码中使用了C++的标准库iostream和cmath,其中iostream库提供了输入输出流,cmath库提供了数学函数sqrt(),用于计算平方根。

在代码中,首先用cin从用户输入获取方程的系数a、b、c,然后计算判别式discriminant,根据判别式的值情况判断一元二次方程的根的类型,并输出计算结果。

在实现过程中,需要注意以下问题:

1. 判别式的值可能为负数,需要特别处理虚数解的情况,并输出虚数部分。

2. 在计算时,除数不为0,需要注意。在这里,我们需要特别考虑a值为0的情况。

3. 输出时,需要根据实际情况添加适当的输出语句。

总的来说,C++编写一元二次方程求根的代码实现并不难,对于初学者来说,可以通过实践巩固自己的编程能力,更好地掌握C++编程语言。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复