努力刷题,每日三题,题目来源于《 Java大学实用教程(第四版)》
第一题
编写一个类,该类的创建对象可以计算等差数列的和。
package homework;
import java.util.Scanner;
public class Demo1 {
static double work(double a,double d,int n){// a:首项 d:公差 n:项数
double sum;
sum = a*n+((n*(n-1))*d)/2;
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入首项:");
double a = scanner.nextDouble();
System.out.println("输入公差:");
double d = scanner.nextDouble();
System.out.println("输入项数:");
int n = scanner.nextInt();
Demo1 demo1 = new Demo1();
double answer = demo1.work(a,d,n);
System.out.println(answer);
}
}
第二题
编写一个类,该类创建了一元二次方程共有的属性和功能,即该类有刻画方程系数的3个成员变量以及计算实根的方法。要求,该类的所有对象共享常数项。
package homework;
import java.util.Scanner;
public class Demo3 {
static class Work{
private double a;
private double b;
private double c;
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public void setA(double a) {
this.a = a;
}
public void setB(double b) {
this.b = b;
}
public void setC(double c) {
this.c = c;
}
static void method(double a, double b, double c){
double temp;
temp = b*b-4*a*c;
if(temp>=0) {
double x1 = (-b + Math.sqrt(temp)) / 2 * a;
double x2 = (-b - Math.sqrt(temp)) / 2 * a;
System.out.println("x1=" + x1);
System.out.println("x2=" + x2);
}else{
System.out.println("此方程无解!");
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入a的值:");
double a = scanner.nextDouble();
System.out.println("输入b的值:");
double b = scanner.nextDouble();
System.out.println("输入c的值:");
double c = scanner.nextDouble();
Work work = new Work();
work.method(a,b,c);
}
}
第三题
编写两个类:A和B,A创建的对象可以计算两个正整数的最大公约数,B创建的对象可以计算两个数的最小公倍数。要求:B类中有一个成员成员变量是用A类声明对象。
package homework;
import java.util.Scanner;
public class Demo4 {
static class A{
public int hanshu(int x,int y){
int c;
c=x%y;
while(c!=0){
x=y;
y=c;
c=x%y;
}
return y;
}
}
static class B {
A a = new A();
public int hanshu1(int x, int y) {
int temp;
temp = (x * y)/(a.hanshu(x, y));
return temp;
}
}
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
int x=scanner.nextInt();
int y=scanner.nextInt();
A a = new A();
int d=a.hanshu(x,y);
B b = new B();
int e =b.hanshu1(x,y);
System.out.println("最大公约数: "+d);
System.out.println("最小公倍数: "+e);
scanner.close();
}
}
打卡。