用c++代码写一段计算一元二次方程根的代码
时间: 2024-06-15 14:07:40 浏览: 92
当然可以!以下是用C++代码写的计算一元二次方程根的示例:
```cpp
#include <iostream>
#include <cmath>
int main() {
double a, b, c;
std::cout << "请输入一元二次方程的系数:\n";
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
std::cout << "c = ";
std::cin >> c;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
std::cout << "方程的两个实根为:" << root1 << " 和 " << root2 << std::endl;
} else if (discriminant == 0) {
double root = -b / (2 * a);
std::cout << "方程有一个实根:" << root << std::endl;
} else {
std::cout << "方程没有实根!" << std::endl;
}
return 0;
}
```
阅读全文