-4

数学.sqrt(X)。以下是它的表格 math.sqrt(X)。以下是它的表格

     public class SqRoots
{     static final int N = 10;  // How many square roots to compute.

     public static void main ( String [] args )
     {
         // Display a title
         System.out.println( "\n Square Root Table" );
         System.out.println( "-------------------" );

         for ( int i = 1; i <= N; ++i ) // loop 
         {
             // Compute and display square root of i
             System.out.println( "   " + i + ":\t" + Math.sqrt( i ) );
         }
       }
    }
4

2 回答 2

2

这是我要做的:

public class SqrtTester {
    public static final int MAX_VALUES = 100;

    public static void main(String [] args) {
        int numValues = ((args.length > 0) ? Integer.valueOf(args[0]) : MAX_VALUES);
        double x = 0.0;
        double dx = 0.1;
        for (int i = 0; i < numValues; ++i) {
            double librarySqrt = Math.sqrt(x);
            double yourSqrt = SqrtTester.sqrt(x);
            System.out.println(String.format("value: %10.4f library sqrt: %10.4f your sqrt: %10.4f diff: %10.4f", x, librarySqrt, yourSqrt, (librarySqrt-yourSqrt)));
            x += dx;
        }
    }

    public static double sqrt(double x) {
        double value = 0.0;
        // put your code to calc square root here
        return value;
    }
}
于 2013-06-04T23:43:38.297 回答
0

首先是简单的部分:“对于从 0 到 10 以 1 为增量的每个 x 值”意味着

for(int x = 0; x < 10; x++) {
    // do something with x
}

更难的部分:“建一张桌子”

我会创建一个类来保存“行”数据:

public class Result {
    private int x;
    private double mathSqrt;
    private double mySqrt;

    public double diff() {
        return mySqrt - mathSqrt;
    }

    // getters and other methods as you need
}

然后在一些代码上使用循环为每个 x 值创建 Result 对象并将它们放在一起。

于 2013-06-04T23:43:58.113 回答