javaBea+jsp实现复数的4则运算
时间: 2024-02-23 12:59:58 浏览: 100
实现复数的四则运算
可以通过定义一个复数类来实现复数的四则运算,结合 JSP 页面进行输入和输出。以下是一个简单的实现:
首先定义一个复数类 Complex,包含实部和虚部两个属性,以及对应的 getter 和 setter 方法。同时实现复数的加、减、乘、除四种运算方法。
```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) {
double real = this.real * c.real - this.imag * c.imag;
double imag = this.real * c.imag + this.imag * c.real;
return new Complex(real, imag);
}
public Complex div(Complex c) {
double denominator = c.real * c.real + c.imag * c.imag;
double real = (this.real * c.real + this.imag * c.imag) / denominator;
double imag = (this.imag * c.real - this.real * c.imag) / denominator;
return new Complex(real, imag);
}
}
```
然后在 JSP 页面中,通过表单获取两个复数的实部和虚部,以及所要进行的运算类型。运算结果通过 JSP 页面进行输出。
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.example.Complex" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>复数四则运算</title>
</head>
<body>
<h1>复数四则运算</h1>
<form action="complex.jsp" method="post">
<label>第一个复数:</label>
实部:<input type="text" name="real1">
虚部:<input type="text" name="imag1"><br>
<label>第二个复数:</label>
实部:<input type="text" name="real2">
虚部:<input type="text" name="imag2"><br>
<label>运算类型:</label>
<select name="op">
<option value="add">加</option>
<option value="sub">减</option>
<option value="mul">乘</option>
<option value="div">除</option>
</select><br>
<input type="submit" value="计算">
</form>
<%
String real1Str = request.getParameter("real1");
String imag1Str = request.getParameter("imag1");
String real2Str = request.getParameter("real2");
String imag2Str = request.getParameter("imag2");
String op = request.getParameter("op");
if (real1Str != null && imag1Str != null && real2Str != null && imag2Str != null && op != null) {
double real1 = Double.parseDouble(real1Str);
double imag1 = Double.parseDouble(imag1Str);
double real2 = Double.parseDouble(real2Str);
double imag2 = Double.parseDouble(imag2Str);
Complex c1 = new Complex(real1, imag1);
Complex c2 = new Complex(real2, imag2);
Complex result = null;
if ("add".equals(op)) {
result = c1.add(c2);
} else if ("sub".equals(op)) {
result = c1.sub(c2);
} else if ("mul".equals(op)) {
result = c1.mul(c2);
} else if ("div".equals(op)) {
result = c1.div(c2);
}
out.println("结果为:" + result.getReal() + "+" + result.getImag() + "i");
}
%>
</body>
</html>
```
这样,在浏览器中访问 complex.jsp 页面,即可进行复数的四则运算。
阅读全文