例4.6 编写一个程序,用来求两个整数或3个整数中的最大数。如果输入两个整数,程序就输出这两个整数中的最大数,如果输入3个整数,程序就输出这3个整数中的最大数。
public class Demo4_6 {
public static void main(String[] args) {
int a=8, b=-12, c=27;
System.out.println("max(a, b, c) = "+max(a,b,c));
System.out.println("max(a, b) = "+max(a,b));
}
public static int max(int a, int b, int c) {
if(b>a)
a = b;
if (c>a)
a = c;
return a;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
}
例4.7 将例4.6程序改为通过函数模板来实现
例4.8 求2个或3个正整数中的最大数,用带有默认参数的函数实现
Java不能设置默认参数,只能通过重载来实现。
例4.9 用弦截法求方程f(x)=x3-5x2+16x-80=0的根
import java.util.Scanner;
public class Demo4_9 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x1, x2, f1, f2, x;
do {
System.out.print("Input x1, x2:");
x1 = sc.nextDouble();
x2 = sc.nextDouble();
f1 = f(x1);
f2 = f(x2);
} while (f1*f2>=0);
x = root(x1, x2);
System.out.println("A root of equation is "+x);
}
private static double f(double x) {
double y;
y = x*x*x-5*x*x+16*x-80;
return y;
}
private static double xpoint(double x1,double x2) {
double y;
y = (x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
return y;
}
private static double root(double x1, double x2) {
double x,y,y1;
y1=f(x1);
do {
x = xpoint(x1,x2);
y = f(x);
if (y*y1>0){
y1 = y;
x1 = x;
} else
x2 = x;
} while (Math.abs(y)>=0.00001);
return x;
}
}