0

My music program currently returns values for all notes and accidentals that equals the frequency of note A in that octave, but I cannot make the frequency output change for different notes or accidentals, i.e.:

A4=440, C4=440, D#5=880, A5=880 etc

Any input re how to amend my source code would be greatly appreciated!

// Calculates frequency (in Hz) of a note
int frequency(string note)
{
    double octave;
    double f_octave;
    double f_sharpflat;
    double frequency;

    //getting octave as an int
    {
        if (note [1] == '#' || note [1] == 'b')
        {
            octave = atoi (&note[2]);
        }
        else
        {
            octave = atoi (&note[1]);
        }

    }

    //putting frequency into right octave
    {
        if (octave < 4)
        {
            f_octave = round (A4 / (pow(2, (4 - octave))));
        }

        else if (octave > 4)
        {
            f_octave = round (A4 * (pow(2, (octave - 4))));
        }

        else
        {
            f_octave = A4;
        }
    }

    //adding sharp or flat
    {
        if (note [1] == '#')
        {
            f_sharpflat = f_octave * (pow(2, 1/12));
        }

        else if (note [1] == 'b')
        {
            f_sharpflat = f_octave / (pow(2, 1/12));
        }

        else
        {
            f_sharpflat = f_octave;
        }
    }

    //adding all notes
    {
        if (note [0] == 'C')
        {
            frequency = f_sharpflat / (pow(2, 9/12));
        }

        else if (note [0] == 'D')
        {
        frequency = f_sharpflat / (pow(2, 7/12));
        }

        else if (note [0] == 'E')
        {
            frequency = f_sharpflat / (pow(2, 5/12));
        }

        else if (note [0] == 'F')
        {
            frequency = f_sharpflat / (pow(2, 4/12));
        }

        else if (note [0] == 'G')
        {
            frequency = f_sharpflat / (pow(2, 2/12));
        }

        else if (note [0] == 'A')
        {
            frequency = f_sharpflat;
        }

        else if (note [0] == 'B')
        {
            frequency = f_sharpflat * (pow(2, 1/12));
        }

        else
        {
            return 0;
        }

    }

    return round(frequency);

}

1 Answer 1

2

When you write 9/12, that's an integer division. Integer division results in an integer again, truncating the result. You want a floating point division instead. For that, make at least one of the operands floating point, for example 9/12.0.

BTW, you could make your code a bit simpler, by just calculating the number of semitones relative to A4, and doing the pow once at the very end of the function. And pow can perfectly handle zero or negative numbers, so no need to differentiate between less than 4 and greater than 4.

You must log in to answer this question.

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