目录
一、Java解一元二次方程
package hello; import java.util.Scanner; public class hey { public static void main(String[] args) { double a,b,c; while(true) { System.out.println("请输入a:"); Scanner sc=new Scanner(System.in); a=sc.nextDouble(); System.out.println("请输入b:"); Scanner sc1=new Scanner(System.in); b=sc.nextDouble(); System.out.println("请输入c:"); Scanner sc2=new Scanner(System.in); c=sc.nextDouble(); if(b*b-4*a*c<0) { System.out.println("该方程无解"); break; } else if(a==0&&b==0) { System.out.println("x任意解"); break; } else { if(a==0) { System.out.println("x无解"); break; } else { double X1=(-b+Math.sqrt(b*b-4*a*c))*1/(2*a); double X2=(-b-Math.sqrt(b*b-4*a*c))*1/(2*a); System.out.println("方程的根为:"+X1); System.out.println("方程的根为:"+X2); break; } } } } }
运行结果
编辑
思路解析
首先要知道一元二次方程如何解,然后就好做了
二、Java四则运算
package hello; import java.util.Scanner; public class hello { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = 0; int a, b; int sum = 0; System.out.println("输入要做的题目的数量:"); n = scanner.nextInt(); int[] op = new int[n]; int[] s = new int[n]; int[] result = new int[n]; String[] questions = new String[n]; for (int i = 0; i < n; i++) { op[i] = (int) (Math.random() * 4); // 运算符 a = (int) (Math.random() * 89) + 10; // 数a b = (int) (Math.random() * 89) + 10; // 数b System.out.println(a + getOp(op[i]) + b + "=?"); System.out.println("输入答案:"); s[i] = scanner.nextInt(); // 输入的答案 result[i] = jisuan(a, b, op[i]); // 正确答案 if (s[i] == result[i]) { sum++; } questions[i] = a + getOp(op[i]) + b + "=" + result[i]; } // 最后的输出 System.out.println("你答对了" + sum + "道题,答错了" + (n - sum) + "道题"); for (int i = 0; i < n; i++) { System.out.print(questions[i]); if (s[i] == result[i]) { System.out.println(",你的回答是" + s[i] + ",正确"); } else { System.out.println(",你的回答是" + s[i] + ",错误"); } } } // 获取运算符 private static String getOp(int index) { String string = ""; switch (index) { case 0: string = "+"; break; case 1: string = "-"; break; case 2: string = "*"; break; case 3: string = "/"; break; } return string; } // 计算答案 private static int jisuan(int a, int b, int index) { int sum = 0; switch (index) { case 0: sum = a + b; break; case 1: sum = a - b; break; case 2: sum = a * b; break; case 3: sum = a / b; break; } return sum; } }
运行结果
编辑
思路解析
思路解析看代码就行