用c++写一个解一元二次方程的程序
时间: 2023-05-19 22:00:52 浏览: 243
好的,以下是一个用 C 语言编写的解一元二次方程的程序:
```
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, delta, x1, x2;
printf("请输入一元二次方程的系数:\n");
printf("a = ");
scanf("%lf", &a);
printf("b = ");
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
delta = b * b - 4 * a * c;
if (delta < 0) {
printf("方程无实数解!\n");
} else if (delta == 0) {
x1 = x2 = -b / (2 * a);
printf("方程有唯一实数解:x1 = x2 = %.2f\n", x1);
} else {
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("方程有两个实数解:x1 = %.2f,x2 = %.2f\n", x1, x2);
}
return 0;
}
```
希望能够帮到你!
相关问题
用c++写一个解一元二次方程的解,设b²-4ac>0
```c
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, delta, x1, x2;
printf("请输入一元二次方程的系数a, b, c:\n");
scanf("%lf%lf%lf", &a, &b, &c);
delta = b * b - 4 * a * c;
if (delta > 0) {
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("方程的两个实数根为 x1=%.2lf, x2=%.2lf\n", x1, x2);
} else if (delta == 0) {
x1 = -b / (2 * a);
printf("方程有两个相等的实数根 x1=x2=%.2lf\n", x1);
} else {
printf("方程没有实数根\n");
}
return 0;
}
```
c++结构体解一元二次方程
以下是一个简单的 C++ 程序,可以用结构体来解一元二次方程:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct QuadraticEquation {
double a, b, c;
};
int main() {
QuadraticEquation eq;
cout << "Enter the coefficients of the quadratic equation (ax^2 + bx + c = 0):" << endl;
cout << "a = "; cin >> eq.a;
cout << "b = "; cin >> eq.b;
cout << "c = "; cin >> eq.c;
double delta = eq.b * eq.b - 4 * eq.a * eq.c;
if (delta > 0) {
double x1 = (-eq.b + sqrt(delta)) / (2 * eq.a);
double x2 = (-eq.b - sqrt(delta)) / (2 * eq.a);
cout << "The equation has two real roots: x1 = " << x1 << ", x2 = " << x2 << endl;
} else if (delta == 0) {
double x = -eq.b / (2 * eq.a);
cout << "The equation has one real root: x = " << x << endl;
} else {
double realPart = -eq.b / (2 * eq.a);
double imagPart = sqrt(-delta) / (2 * eq.a);
cout << "The equation has two complex roots: x1 = " << realPart << " + " << imagPart << "i, x2 = " << realPart << " - " << imagPart << "i" << endl;
}
return 0;
}
```
该程序使用 QuadraticEquation 结构体存储方程的系数,然后计算方程的根(如果有)。如果 delta 大于 0,则方程有两个实数根;如果 delta 等于 0,则方程有一个实数根;否则,方程有两个复数根。
阅读全文