0

I am working on pset3 music frequency. I struggled with finding a pattern of frequencies for different notes, so instead, i created two arrays one with all possible note (C,D,E,F,G,A,B) and another one with frequencies for note in octave 4 (C4,D4,E4...). However, when I test the code, all inputs return 0. I could not figure out whats wrong with the code. Please take a look for me. Thank you.

int frequency(string note)
{
    char notes[ ] = {'C', 'D', 'E', 'F', 'G', 'A', 'B'};
    float octave4[ ] = {pow(2.0, -9 / 12), pow(2.0, -7 / 12), pow(2.0, -5 / 12), pow(2.0, -4 / 12), pow(2.0, -2 / 12), pow(2.0, 1.0), pow(2.0, 2 / 12)};
    char *i = strchr(notes, note[0]);
    int q = *i - 48;
    if(isdigit(note[1]))
    {
        int j = note[1] - 48;
        float hertz = octave4[q] * 440 * pow(2, j-4);
        return(round(hertz));
    }
    else
    {
        int k = note[2] - 48;
        if(note[1] == '#')
        {
            float hertz2 = octave4[q] * 440 * pow(2, k-4) * pow(2, 1/12);
            return(round(hertz2));
        }
        if(note[1] == 'b')
        {
            float hertz3 = octave4[q] * 440 * pow(2, k-4) * pow(2, -1/12);
            return(round(hertz3));
        }
    }
    return false;
}

enter image description here

2
  • Hi. Can you please edit your question? Please remove the screenshot and cut and paste the actual code? thanks. – Cliff B Jul 22 '18 at 21:15
  • Sure, I actually modified my code. I will copy it. Thank you – Issa Jul 22 '18 at 21:18
0

There are several issues. The first lies here:

float octave4[ ] = {pow(2.0, -9 / 12), pow(2.0, -7 / 12), pow(2.0, -5 / 12), pow(2.0, -4 / 12), pow(2.0, -2 / 12), pow(2.0, 1.0), pow(2.0, 2 / 12)};

All of those divisions in the second parameter are integer divisions, resulting in 0. (Review integer division if you don't know why.) Check for this elsewhere in the code too.

Next, look at this:

char *i = strchr(notes, note[0]);
int q = *i - 48;

I believe you're looking for the octave number, but the code is actually subtracting 48 from the note letter, not the octave number. (I think.)

From this point on, the errors cascade, so it would be best to fix the first issues and run it under debug50 to see what it actually does. Pay special attention to the variable contents as you step through.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you for your answer. For char *i = strchr(notes, note[0]); int q = *i - 48; I am actually trying to find note[0]'s location i in notes[ ], that way i know whether the note is C, D, E or .... then I can use the same location i in octave4[ ] to get corresponding frequency. clearly this does not work out and i do not know how to fix it... – Issa Jul 22 '18 at 22:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .