显示完整javaBean和完整jsp实现复数的4则运算
时间: 2024-02-23 18:00:55 浏览: 71
JavaBean+Servlet+jsp实现分页显示(原创)
4星 · 用户满意度95%
完整的JavaBean代码如下:
```java
public class Complex {
private double real; // 实部
private double imag; // 虚部
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImag() {
return imag;
}
public void setImag(double imag) {
this.imag = imag;
}
// 定义复数的加法
public Complex add(Complex c) {
return new Complex(this.real + c.real, this.imag + c.imag);
}
// 定义复数的减法
public Complex sub(Complex c) {
return new Complex(this.real - c.real, this.imag - c.imag);
}
// 定义复数的乘法
public Complex mul(Complex c) {
return new Complex(this.real * c.real - this.imag * c.imag,
this.real * c.imag + this.imag * c.real);
}
// 定义复数的除法
public Complex div(Complex c) {
double d = c.real * c.real + c.imag * c.imag;
return new Complex((this.real * c.real + this.imag * c.imag) / d,
(this.imag * c.real - this.real * c.imag) / d);
}
}
```
完整的JSP代码如下:
```jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="Complex" %>
<html>
<head>
<title>复数四则运算</title>
</head>
<body>
<jsp:useBean id="complex1" class="Complex" scope="page">
<jsp:setProperty name="complex1" property="real" value="1" />
<jsp:setProperty name="complex1" property="imag" value="2" />
</jsp:useBean>
<jsp:useBean id="complex2" class="Complex" scope="page">
<jsp:setProperty name="complex2" property="real" value="3" />
<jsp:setProperty name="complex2" property="imag" value="4" />
</jsp:useBean>
<%
Complex result = complex1.add(complex2);
complex1.setReal(5);
complex1.setImag(6);
complex2.setReal(7);
complex2.setImag(8);
result = complex1.sub(complex2);
complex1.setReal(9);
complex1.setImag(10);
complex2.setReal(11);
complex2.setImag(12);
result = complex1.mul(complex2);
complex1.setReal(13);
complex1.setImag(14);
complex2.setReal(15);
complex2.setImag(16);
result = complex1.div(complex2);
%>
<p>复数1:${complex1.real}+${complex1.imag}i</p>
<p>复数2:${complex2.real}+${complex2.imag}i</p>
<p>复数1+复数2:${complex1.add(complex2).real}+${complex1.add(complex2).imag}i</p>
<p>复数1-复数2:${complex1.sub(complex2).real}+${complex1.sub(complex2).imag}i</p>
<p>复数1*复数2:${complex1.mul(complex2).real}+${complex1.mul(complex2).imag}i</p>
<p>复数1/复数2:${complex1.div(complex2).real}+${complex1.div(complex2).imag}i</p>
</body>
</html>
```
阅读全文