0

在提示的第 1 部分中,我希望将一个方程集成到 Java 中以获得一个周期 (T) 的值。等式如下:T = FS / (440 * (2 ^(h/12))

笔记:

FS = 采样率,即 44100 / 1。

h = 半步,由用户提供。

这个等式的一个例子是:44100 / (440 * (2 ^(2/12)) = 89.3

我写的代码如下:

public static double getPeriod(int halfstep) {
    double T = 100; // TODO: Update this based on note
    
    double FS = 44100 / 1;
    double power = Math.pow(2, (halfstep / 12));
    double denominator = 440 * (power);
    double result = (FS) / (denominator);
    T = Math.round(result);
    
    return T;
}

// Equation test.
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("halfstep is: ");
    int halfstep = in.nextInt();
    
    double period = getPeriod(halfstep);
    System.out.print("Period: " + period + " ");
}

但是当我使用 h = 2, T = 100.0 而不是预期的 89.3 运行这段代码时,我不确定问题是什么。有什么想法吗?

4

1 回答 1

0

因为halfStep是一个int,当你写

(halfstep / 12)

计算是通过取halfStep / 12并向下舍入到最接近的整数来完成的。因此,如果您在此处插入 2,那么halfStep / 12将返回 0 而不是 1/6。这会打乱计算,很可能是什么给了你错误的答案。

对于如何在此处进行操作,您有几个选项。一个是更改halfStep为 adouble而不是int. 另一个是将部门重写为

halfStep / 12.0

由于12.0double文字,它将以您想要的方式执行除法。

另一个潜在问题 - 您将变量声明T100.0,但从不在T计算中的任何地方使用并最终在返回之前覆盖它。我不确定这是否是故意的,或者这是否表明其中一个公式不正确。

希望这可以帮助!

于 2020-06-23T18:41:21.593 回答