簡體   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