/* The modern piano usually contains 88 keys that produce sound at frequencies between 27 and 4200 Hz. For example, key number 49 plays the note A4, which corresponds to sound at 440 Hz. The frequency f of a key can be computed from its number n using the following exponential function: f(n) = 440 x 2^((n-49)/12) Your goal is to solve the inverse problem: given a frequency (f) compute the number for the key that produces sound with the frequency closest to f. In addition to the number, your program also has to print the number of the octave in which the key falls (i.e., octave 0, or octave 1, or octave 2, etc.) The number of the octave o can be computed from the number of the key n using the following C expression: o = (n + 8) /12, where both o and n are assumed to be integers. Hint: To obtain n from f you can use the following equation: n = 12 * log (f/440) + 49 2 Because the key number must be an integer, you will need to round the value of the right-hand side of the above equation to the nearest integer. Thus, 49.3 rounds to 49 and 49.6 rounds to 50. Selecting the mode for rounding the exact halves is up to you. In other words, 49.5 may round to 50 or to 49. Remember that assigning a floating point value to an integer in C simply truncates its fractional part, which is not what is needed here. Hint 2: The standard mathematical function log() computes the natural logarithm, i.e., logarithm base e. You will need to use the change of base formula, i.e., divide the value returned by log() by the value of log(2.0). ============= START OF SAMPLE RUN ======================= Enter the key frequency> 440 The piano key that produces frequency closes to 440 is key number 49. This key is in octave 4. ============= END OF SAMPLE RUN ======================= ============= START OF SAMPLE RUN ======================= Enter the key frequency> 553 The piano key that produces frequency closes to 553 is key number 53. This key is in octave 5. ============= END OF SAMPLE RUN ======================= ============= START OF SAMPLE RUN ======================= Enter the key frequency> 35.900 The piano key that produces frequency closes to 35.9 is key number 6. The key is in octave 1. ============= END OF SAMPLE RUN ======================= */ #include #include int getkey(double f) { double n = 12 * log(f / 440) / M_LN2 + 49; return n + 0.5; // round to nearest } int main() { double f; printf("Enter the key frequency> "); scanf("%lf", &f); int n = getkey(f); printf("The piano key that produces frequency closes to %g is key number %d.\n" "The key is in octave %d.\n", f, n, (n + 8) / 12); return 0; }