【发布时间】:2016-06-24 00:20:04
【问题描述】:
嗯,这是一个基本程序,我得到了一个字符数组,比如:
char alphabet[5] = {'A', 'B2', 'C', 'D4', 'E'};
我想在 for 循环中打印该数组的元素:
int remainder = my_number % 5;
printf("%c\n", alphabet[remainder]);
那就是我无法让它按预期运行的地方打印出来了
A、2、C、4 或 E。我怎样才能让它打印B2和D4?
我听说过使用枚举,但我不明白如何使用,我对元素具有价值的想法以及如何使用它们的价值获取元素感到困惑,例如:enum letters {'a', 'b', 'c'}; a = 0, b = 1 和 c = 2。
(也许只是我的语法不正确,但如果你能帮助我,请...)
我将打开我的代码以便于解释。
#include <stdio.h>
#include <stdlib.h>
const char *notes[13] = {"C", "C2", "D", "D2", "E", "F", "F2", "G", "G2", "A", "A2", "B", "c"}; // The 2's is for the "#"
int main(int argc, char const *argv[]) // Just using argv[1] to say how much numbers I want to print
{
int now, before_1 = 1, before_2 = 1, rem, steps; // "rem" stands for remainder
char note;
if (atoi(argv[1]) <= 2)
for (steps = 0; steps < atoi(argv[1]); steps++)
printf("1\n");
else
for (steps = 0; steps < atoi(argv[1]); steps++) // Main loop for Fibonacci's Numbers
{
now = before_1 + before_2;
rem = now % 13;
note = notes[rem];
printf("Note : %c <=> Rem : %d. Num : %d\n", note, rem, now);
before_2 = before_1; // Change values of variables
before_1 = now;
}
return 0;
}
这个想法是获取斐波那契系列的数字并将它们转换为所有可能的 13 个音符(包括尖锐的音符),但正如我所说的,输出的音符太好了。
【问题讨论】:
-
B2和D4不是字符。 -
它们是字符串吗?
-
@tkausl:它们是有效的字符常量。只是作为
char对象的初始化器可能不正确。 -
但在这种情况下,它应该只打印
B和D,因为它们确实是字符,对吧? @tkausl @Olaf -
不清楚你想要什么。 1)字母通常是单个字母,那么您希望在某些条目中包含两个字符的原因是什么? 2)
enumss 是非常不同的东西。 3)char通常采用 one 字符。它绝对不是“字符串”。 4)如果您想要一个“字符串”,请使用 C 字符串。 5) C 没有字符串type。这是关于如何使用char数组的所有约定。 6) 数组与指针不同! 7) 所有这些都将在任何优秀的 C 书籍中进行解释。