输入x值,按照公式计算cos(x)的值,直到最后一项小于10-6为止。
1 package repeat_job1; 2 3 public class Cos { 4 public Cos(){} 5 public static double cos(double x) 6 { 7 double cos=1,numerator=1,denominator=1; 8 int k=1; 9 while(Math.abs(numerator/denominator)>1e-6) 10 { 11 numerator*=x*x; 12 denominator *=- (2*k)*(2*k-1); 13 cos+=numerator/denominator; 14 k++; 15 } 16 return cos; 17 } 18 19 20 }
import repeat_job1.Cos; import java.util.Scanner; public class Test3 { public static void main(String[] args) { Scanner reader=new Scanner(System.in); System.out.println("请输入x:"); double x=reader.nextDouble(); reader.close(); System.out.println("cos("+x+")="+Cos.cos(x)); } }