gpt4 book ai didi

Java - 实数幂 n^k

转载 作者:行者123 更新时间:2023-12-01 06:41:17 27 4
gpt4 key购买 nike

我在编写程序来解决 Java 教科书上的这个练习时遇到困难:

Write a method raiseRealToPower that takes a floating-point value x and an integer k and returns xk. Implement your method so that it can correctly calculate the result when k is negative, using the relationship x^(-k) = 1 / x^k.

Use your method to display a table of values of πk for all values of k from –4 to 4.

我没有用 PI 完成这部分,我知道,如果我的程序开始工作...这就是我所做的...请告诉我,出了什么问题。

import acm.program.*;

public class vjezba55 extends ConsoleProgram {

private static final double PI = 3.14159253;

public void run() {
double x = readDouble ("x: ");
double k = readDouble ("k: ");
println ("x^k = " + raiseDoublePower(x,k));
}

/* Method that counts x^k */
private double raiseDoublePower (double x, double k){
if (k >= 0) {
return Math.pow(x, k);
}
else {
double total = 1;
for (int i= 0; i>k; i--) {
total = (double) 1 / x;
}
return total;
}
}
}

最佳答案

看看你的循环代码。您只是在每次迭代中从头开始重新计算 total,而不是更新之前的结果。

关于Java - 实数幂 n^k,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6974541/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com