cs50 pset3,频率功能不工作

cs50 pset3, frequency function not working

我对 C 语言完全陌生,这门课程是我第一次尝试 C。

题目要求计算return音符出现的频率。频率是根据 A4 中音符的相对位置计算的。 Here 是完整的问题。

使用调试器后,我发现 freq 变量的值在 switch 语句中没有更新,我不知道为什么。

#include <math.h>
#include <stdio.h>
#include <cs50.h>

int frequency(string note)
{


    char n = note[0]; //first character is a note 'A, B..'
    float freq = 0.0;

    //second character can be an accidental or an octave
    if (note[1] == '#' || note[1] == 'b')
    {
        int octave = note[2] - '0';
        freq = 440 * powf(2, octave - 4); //frequency of note 'A' taken as base

        switch (n) // changing frequency depending upon the relative position of note from A
        {
            case 'C':
                freq = freq / powf(2, 9/12); //C is 9 semitones away from A
                break;

            case 'D':
                freq = freq / powf(2, 7/12);
                break;

            case 'E':
                freq = freq / powf(2, 5/12);
                break;

            case 'F':
                freq = freq / powf(2, 4/12);
                break;

            case 'G':
                freq = freq / powf(2, 2/12);
                break;

            case 'B':
                freq = freq * powf(2, 4/12);
                break;
        }

        //changing frequency depending upon # of b
        if (note[1] == '#')
        {
            freq = round(freq * powf(2, 1/12));
        }
        else
        {
            freq =  round(freq / powf(2, 1/12));
        }

    }
    else
    {
        int octave = note[1] - '0';
        freq = 440 * powf(2, octave - 4);//frequency of note A taken as base

        switch (n) // changing frequency depending upon the relative position of note from A
        {
            case 'C':
                freq  = round(freq / powf(2, 9/12));
                break;

            case 'D':
                freq  = round(freq / powf(2, 7/12));
                break;

            case 'E':
                freq  = round(freq / powf(2, 5/12));
                break;

            case 'F':
                freq  = round(freq / powf(2, 4/12));
                break;

            case 'G':
                freq  = round(freq / powf(2, 2/12));
                break;

            case 'A':
                freq  = round(freq);
                break;

            case 'B':
                freq  = round(freq * powf(2, 4/12));
                break;
        }
    }

    return freq;

}

int main(void)
{
    printf("%i\n", frequency("C5"));
    printf("%i\n", frequency("C#5"));

}

以上代码的输出

880
880

预期输出

523
554

880是A5的频率

powf(2, 9/12)

将给出结果 1,因为 9/12 是使用整数计算的。

即:powf(2, 9/12)等同于powf(2, 0)

尝试

powf(2, 9.0/12)

而是强制使用浮点数来计算 9 除以 12。