用JS设计一个一元二次方程求解功能的类
时间: 2024-05-27 18:10:50 浏览: 18
class QuadraticEquationSolver {
constructor(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
solve() {
const delta = this.b ** 2 - 4 * this.a * this.c;
if (delta < 0) {
return "无实数解";
} else if (delta === 0) {
const x = (-this.b / (2 * this.a)).toFixed(2);
return `有一个实数解:x=${x}`;
} else {
const x1 = ((-this.b + Math.sqrt(delta)) / (2 * this.a)).toFixed(2);
const x2 = ((-this.b - Math.sqrt(delta)) / (2 * this.a)).toFixed(2);
return `有两个实数解:x1=${x1}, x2=${x2}`;
}
}
}
const equation = new QuadraticEquationSolver(1, -2, -3);
console.log(equation.solve()); // 有两个实数解:x1=3.00, x2=-1.00
相关问题
设计一个一元二次方程求解功能的类
class QuadraticEquationSolver:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def solve(self):
discriminant = self.b ** 2 - 4 * self.a * self.c
if discriminant < 0:
return None, None
elif discriminant == 0:
x = -self.b / (2 * self.a)
return x, None
else:
x1 = (-self.b + discriminant ** 0.5) / (2 * self.a)
x2 = (-self.b - discriminant ** 0.5) / (2 * self.a)
return x1, x2
# 使用方法
solver = QuadraticEquationSolver(1, 2, 1)
x1, x2 = solver.solve()
if x1 is None:
print("无解")
elif x2 is None:
print("唯一解:", x1)
else:
print("两个解分别为:", x1, x2)
设计一个一元二次方程类,并为这个类添加异常处理
好的,我可以为您设计一个一元二次方程类,并为其添加异常处理。
以下是一个示例代码:
```python
class QuadraticEquation:
def __init__(self, a, b, c):
if a == 0:
raise ValueError("a不能为0")
self._a = a
self._b = b
self._c = c
def solve(self):
delta = self._b ** 2 - 4 * self._a * self._c
if delta < 0:
raise ValueError("无实数解")
elif delta == 0:
x = -self._b / (2 * self._a)
return x
else:
x1 = (-self._b + delta ** 0.5) / (2 * self._a)
x2 = (-self._b - delta ** 0.5) / (2 * self._a)
return x1, x2
```
在上述代码中,我们首先定义了一个`QuadraticEquation`类,并在其构造函数中添加了异常处理。当输入的参数`a`为零时,我们会抛出一个`ValueError`异常,以提醒用户重新输入。
接着,我们定义了一个`solve`方法,用于求解一元二次方程的解,并在其中添加了两种异常处理。当判别式小于零时,我们抛出`ValueError`异常,以提醒用户该方程无实数解。当判别式等于零时,我们直接返回一个解。当判别式大于零时,我们计算两个解并返回。
这样,我们就成功地为一元二次方程类添加了异常处理,使其更加健壮和可靠。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)