我如何将随机生成的整数分配给 C 中的字符串?

how can i assign a randomly generated integer to a string in C?

我正在尝试制作老虎机类型的东西,我想将随机生成的数字分配给某些符号,例如 1 = cherry、2 = bell 等等,这样我就可以以符号形式打印出结果结束。

我尝试将符号作为字符串放入数组中,并在每个槽函数中将数字分配给数组中的元素,但没有成功...有没有办法做到这一点?

这是我到目前为止编写的代码,减去了数组尝试。任何的意见都将会有帮助! :D

编辑: 这是我在其中一个插槽上尝试做的事情的示例,但它一直说我需要强制转换来从指针分配整数(我'我试过在线搜索,但不知道该怎么做)

char * slotOne(int randOne, const char *symbols[]) 
{ 
    randOne = rand() % 4 + 1; 

    if (randOne = 1)
    {
        randOne = *symbols;
    }
    if (randOne = 2)
    {
        randOne = *(symbols+1);
    }
    if (randOne = 3)
    {
        randOne = *(symbols+2);
    }
    else
    {
        randOne = *(symbols+3);
    }
    return randOne; 

}

这是我尝试声明字符串数组的主要函数的一部分:

int main() 
{ 
    int x, one, two, three;
    const char *symbols[4] = {"bell", "orange", "cherry", "horseshoe"};

    srand(time(NULL)); 

    one = slotOne(x);
    two = slotTwo(x);
    three = slotThree(x); 

    printf("%s - %s - %s\n", one, two, three); 

    //...

} 

不确定 %s 或 %c 是否也是正确的类型...

至少这些问题:


代码在应该比较 ==.

时分配 =
// if (randOne = 1)
if (randOne == 1)

最后一个 if () { ... } else { ... } 将导致执行 2 个块之一。 OP 想要一棵 if () { ... } else if () { ... } else { ... } 树。

// Problem code
if (randOne = 3) {
    randOne = *(symbols+2);
} else {
    randOne = *(symbols+3);
}

建议

if (randOne == 1) {
    randOne = *symbols;
} else if (randOne == 2) {
    randOne = *(symbols+1);
} else if (randOne == 3) {
    randOne = *(symbols+2);
} else {
    randOne = *(symbols+3);
}

同时研究 switch

switch (randOne) {
  case 1:
    randOne = *symbols;
    break;
  case 2:
    randOne = *(symbols+1);
    break;
  case 3:
    randOne = *(symbols+2);
    break;
  default:
    randOne = *(symbols+3);
    break;
}

或考虑编码解决方案:

randOne = *(symbols+(randOne-1));

但是代码需要 return 指向 字符串的指针 而不是 int 并且不需要将 randOne 作为参数.

const char * slotOne(const char *symbols[]) { 
    int randOne = rand() % 4; 
    return symbols[randOne];
}

调用代码也需要调整以接收 const char *,而不是 int

// int one;
// one = slotOne(x);
const char *one = slotOne(symbols);