1. 程式人生 > 實用技巧 >2020.8.16第四十一天

2020.8.16第四十一天

例4.7弦截法求方程f(x)=x^3-5x^2+16x-80=0的根

 1 import java.util.Scanner;
 2 import java.lang.*;
 3 public class cjava {
 4     public static void main(String[] args) {
 5         double x1,x2,f1,f2,x;
 6         Scanner a=new Scanner(System.in);
 7         do
 8         {
 9             System.out.println("input x1,x2:");
10 x1=a.nextDouble(); 11 x2=a.nextDouble(); 12 f1=f(x1); 13 f2=f(x2); 14 }while(f1*f2>=0); 15 x=root(x1,x2); 16 System.out.println("A root of equation is "+x); 17 } 18 static double f(double x) { 19 double y; 20 y=x*x-5*x+16*x-80;
21 return y; 22 } 23 static double xpoint(double x1,double x2) 24 { 25 double y; 26 y=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1)); 27 return y; 28 } 29 static double root(double x1,double x2) 30 { 31 double x,y,y1; 32 y1=f(x1); 33 do
34 { 35 x=xpoint(x1,x2); 36 y=f(x); 37 if(y*y1>0) 38 { 39 y1=y; 40 x1=x; 41 } 42 else 43 x2=x; 44 }while(Math.sqrt(y)>=0.00001); 45 return x; 46 } 47 }

例4.8遞迴的方法求n!

 1 import java.util.Scanner;
 2 import java.lang.*;
 3 public class cjava {
 4     public static void main(String[] args) {
 5         int n;
 6         long y;
 7         Scanner a=new Scanner(System.in);
 8         System.out.println("please input an integer:");
 9         n=a.nextInt();
10         y=fac(n);
11         System.out.println(n+"!="+y);
12     }
13     static long fac(int n) {
14         long f;
15         if(n<0)
16         {
17             System.out.println("n<0,data error!");
18             f=-1;
19         }
20         else if(n==0||n==1) f=1;
21         else f=fac(n-1)*n;
22         return f;
23     }
24 }

2.遇到的問題:c++中許多的用法java是沒有的

3.明天繼續寫例題