本文最后更新于657 天前,其中的信息可能已经过时,如有错误请发送邮件到echobydq@gmail.com
Java——求解一元n次方程(V1.0)
主要思路
- 通过 接口(interface) 进行求解方法声明,通过 implements 声明自己使用的接口
- 通过字符串 equals() 方法以及 while() 循环进行选择是否退出程序
- switch case 语句判断求解的方程次幂
代码
/*
@author big_fw
@function 求解一元n次方程
@version 1.o
*/
import java.util.Map;
import java.util.Scanner;
interface Solve1 { //一元一次
double solve1(double a, double b, double y);
}
interface Solve2 { //一元二次
double solve2(double a, double b, double c);
}
public class SolveEquation implements Solve1, Solve2 {
//一元一次
public double solve1(double a, double b, double y) {
double x;
x = (y - b) / a;
return x;
}
//一元二次
public double solve2(double a, double b, double c) {
double x, x1;
x1 = b * b - 4 * a * c;
x = Math.sqrt(x1);
return x; //返回 b^2-4ac
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = "q";
System.out.println("进入程序请输入i,如要退出程序请输入 'q':");
String str2 = scan.next();
while (!str2.equals(str1)) {
System.out.print("请选择输入的一元n次方程的次幂:");
int n = scan.nextInt();
switch (n) {
case 1://一元一次方程
SolveEquation s1 = new SolveEquation();
System.out.println("输入一元一次方程,其形式为 ax + b = y");
System.out.print("a为:");
double a = scan.nextDouble();
System.out.print("b为:");
double b = scan.nextDouble();
System.out.print("y为:");
double y = scan.nextDouble();
System.out.println("方程解为:" + s1.solve1(a, b, y));
break;
case 2://一元二次方程
SolveEquation s2 = new SolveEquation();
System.out.println("输入一元二次方程,其形式为 ax^2+bx+c=0(其中a != 0)");
System.out.print("a为:");
double a1 = scan.nextDouble();
System.out.print("b为:");
double b1 = scan.nextDouble();
System.out.print("c为:");
double c1 = scan.nextDouble();
if (b1 * b1 - 4 * a1 * c1 < 0) {
System.out.println("方程无实解");
} else if (b1 * b1 - 4 * a1 * c1 >= 0) {
double x3 = s2.solve2(a1, b1, c1);
double x1 = (-b1 + x3) / (2 * a1);
double x2 = (-b1 - x3) / (2 * a1);
System.out.println("一元二次方程的解为:");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
break;
}
default:
System.out.println("还没写好 ^_^");
}
}
}
}