繁体   English   中英

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

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

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

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

这是我到目前为止编写的代码,减去数组尝试。 任何的意见都将会有帮助! :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));

但是代码需要返回一个指向字符串而不是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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM