## 如何实现CS 50的pset 3频率和理解注释。内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (88)

1)有一条线`for (int i = 0, n = sizeof(NOTES) / sizeof(string); i < n; i++)``notes.c`

2)以下是我对“频率”的实施情况：

```int frequency(string note)
{
char N[2];
int octave;
//parsing the string into a note...
strncpy(N, note, (strlen(note) - 1));
//...and its octave
octave = note[strlen(note) - 1] - '0';
int semitone;
if (strcmp(N, "C") == 0)
semitone = 1;
if (strcmp(N, "C#") == 0 || strcmp(N, "Db") == 0)
semitone = 2;
if (strcmp(N, "D") == 0)
semitone = 3;
if (strcmp(N, "D#") == 0 || strcmp(N, "Eb") == 0)
semitone = 4;
if (strcmp(N, "E") == 0)
semitone = 5;
if (strcmp(N, "F") == 0)
semitone = 6;
if (strcmp(N, "F#") == 0 || strcmp(N, "Gb") == 0)
semitone = 7;
if (strcmp(N, "G") == 0)
semitone = 8;
if (strcmp(N, "G#") == 0 || strcmp(N, "Ab") == 0)
semitone = 9;
if (strcmp(N, "A") == 0)
semitone = 10;
if (strcmp(N, "A#") == 0 || strcmp(N, "Bb") == 0)
semitone = 11;
if (strcmp(N, "B") == 0)
semitone = 12;
//calculate freq: semitones
float freq = 440 * (powf(2, (semitone -10) / (float)12));
//calculate freq: multiply by num of octaves
return round(freq * (powf(2, octave - 4)));
}```

/注释之后的输出是：

``` C4: 262
C#4: 922746880
D4: 294
helpers.c:55:12: runtime error: value 5.85908e+09 is outside the range of representable values of type 'int'
D#4: -2147483648
E4: 330
F4: 349
F#4: -2147483648
G4: 392
G#4: -2147483648
A4: 440
A#4: -2147483648
B4: 494```

### 2 个回答

`string`错误1类型的别名。`char *`(指针)`char`c没有实际的“字符串”数据类型；字符串表示为字符值的序列，后面跟着一个0值终止符。`"hello"`由序列表示`{'h', 'e', 'l', 'l', 'o', 0}`.终止0很重要-如果没有它，各种库例程如`strcpy``strlen``printf`不会将序列识别为字符串。

`string == char *``sizeof (string) == sizeof (char *)`，它是`char *``NOTES`显然是`char *`，所以`sizeof(NOTES)`中的字节数。`NOTES`阵列除法`sizeof(NOTES)`通过`sizeof(string)`中的元素数。`NOTES`阵列。

1. `cs50.h`头文件创建`string`我想把C的，呃，独树一帜字符串和数组语义。不幸的是，这在CS 50学生中造成了很大的混乱。我个人认为这是创建CS 50课程的人的一个错误。
2. 从技术上讲，“存储单元”，但存储单元实际上是一个字节。

```//parsing the string into a note...
char N = note[0];
//...and its octave
int octave = note[strlen(note) - 1] - '0';
int semitone;
if (N == 'C')
semitone = 1;
if (N == 'D')
semitone = 3;
if (N == 'E')
semitone = 5;
if (N == 'F')
semitone = 6;
if (N == 'G')
semitone = 8;
if (N == 'A')
semitone = 10;
if (N == 'B')
semitone = 12;