首页 > 解决方案 > 如何在方法中打印出结果?

问题描述

我需要打印出方法 power2 的结果。如何将它放入变量 long a 中?long a = power2(d,n)的部分有错误;

public class homework {
public static void main(String[] args) {
long starttime = System.nanoTime();
long a = power2(d , n);
long t = System.nanoTime() - starttime;
System.out.println("result1():" + a + ": " + t + "ns");
}
public static double power2(double d, long n) {
double r = 1;
while(n != 0) {
    if(n%2 == 1) {
        r*=d;
    }
    n = n >> 1;
    d = d * d;
}
return r;
}



}

标签: java

解决方案


就这么简单:

public class homework {

public static void main(String[] args) {
     long starttime = System.nanoTime();
     long a = power2(TheDoubleVariable, The LongVariable);
     long t = System.nanoTime() - starttime;
     System.out.println("result1():" + a + ": " + t + "ns");
}

public static double power2(double d, long n) {
    double r = 1;
    while(n != 0) {
        if(n%2 == 1) {
            r*=d;
        }
    n = n >> 1;
    d = d * d;
    }
    return r;
    }
}

推荐阅读