268,537 views
28 votes
28 votes
5.30 LAB: Musical note frequencies

On a piano, a key has a frequency, say f0. Each higher key (black or white) has a frequency of f0 * rn, where n is the distance (number of keys) from that key, and r is 2(1/12). Given an initial key frequency, output that frequency and the next 4 higher key frequencies.

Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);

Ex: If the input is:

440.0
(which is the A key near the middle of a piano keyboard), the output is:

440.00 466.16 493.88 523.25 554.37
Note: Use one statement to compute r = 2(1.0/12.0) using the pow function. Then use that r in subsequent statements that use the formula fn = f0 * rn with n being 1, 2, 3, and finally 4.

User Geoff Dawdy
by
2.6k points

1 Answer

12 votes
12 votes

Answer:

public static void main(String[] args) {

double f0 = 440.0;

double r = Math.pow(2, 1.0/12.0);

for(int n=0; n<=4; n++) {

double f = f0 * Math.pow(r,n);

System.out.printf("%.2f ", f);

}

}

Step-by-step explanation:

You could also do it with a running variable, much shorter, but not using the formula as required:

public static void main(String[] args) {

double f = 440.0;

double r = Math.pow(2, 1.0/12.0);

for(int n=0; n<=4; n++) {

System.out.printf("%.2f ", f);

f *= r;

}

}

User Sumit Bijvani
by
3.2k points