解一元n次方程的代码
时间: 2024-02-20 14:59:44 浏览: 31
以下是解一元n次方程的 Python 代码示例:
```python
import numpy as np
# 求解一元n次方程
def solve_equation(coefficients, constant):
n = len(coefficients)
if n != len(constant):
return None
A = np.zeros((n, n))
b = np.zeros((n, 1))
for i in range(n):
A[i] = np.power(coefficients, n - i - 1)
b[i] = constant[i]
x = np.linalg.solve(A, b)
return x.flatten().tolist()
# 示例
coefficients = [1, 2, 3] # 系数列表,对应x^2, x^1, x^0
constant = [4, 5, 6] # 常数列表
x = solve_equation(coefficients, constant)
print(x) # 输出 [1.0, -2.0, 3.0],即解为x^2 - 2x + 3 = 0
```
需要注意的是,此代码仅适用于一元n次方程的求解,如果输入的系数和常数不符合要求,或者方程无解或有无数解的情况没有进行处理。
相关问题
C语言解一元二次方程代码
以下是一个C语言解一元二次方程的代码示例:
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, x1, x2, delta;
printf("请输入一元二次方程的系数a, b, c:\n");
scanf("%f%f%f", &a, &b, &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++ 解一元二次方程代码
请看下面的代码:
#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 < )
{
printf("方程无实数根!\n");
}
else if (delta == )
{
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 ;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)