打印数学函数值表的程序

来源:互联网 发布:ahocorasick 算法 编辑:程序博客网 时间:2024/06/04 00:21

代码如下:

package com.corejava.test;import java.lang.reflect.Method;public class MethodTest {public static void main(String[] args) throws Exception {Method square = MethodTest.class.getMethod("square", double.class);Method sqrt = Math.class.getMethod("sqrt", double.class);printTable(1,10,10,square);printTable(1,10,10,sqrt);}public static double square(double x){return x*x;}public static void printTable(int from, int to, int n, Method f) {System.out.println(f);double dx=(to-from)/(n-1);for(double x=from;x<=to;x+=dx){try {double y = (double) f.invoke(null, x);System.out.printf("%10.4f | %10.4f%n", x,y);} catch (Exception e) {e.printStackTrace();}}}}

结果打印如下:

public static double com.corejava.test.MethodTest.square(double)    1.0000 |     1.0000    2.0000 |     4.0000    3.0000 |     9.0000    4.0000 |    16.0000    5.0000 |    25.0000    6.0000 |    36.0000    7.0000 |    49.0000    8.0000 |    64.0000    9.0000 |    81.0000   10.0000 |   100.0000public static double java.lang.Math.sqrt(double)    1.0000 |     1.0000    2.0000 |     1.4142    3.0000 |     1.7321    4.0000 |     2.0000    5.0000 |     2.2361    6.0000 |     2.4495    7.0000 |     2.6458    8.0000 |     2.8284    9.0000 |     3.0000   10.0000 |     3.1623


0 0