我正在嘗試創建一個擲骰子游戲,用戶一次最多可以擲 6 個骰子。我試圖通過將指標集成到我的代碼中來實作這一點。我得到一個輸出,用戶給出了所需的卷數,但輸出不正確。它正在列印圖案而不是列印亂數。任何幫助表示贊賞。
你想擲幾個骰子?
用戶輸入: 4
輸出: 3 0 3 0
你想擲幾個骰子?
用戶輸入: 5
輸出: 4 0 4 0 4
#include <stdio.h>
#include <stdlib.h>
void tossDie(int []);
int main() {
int diceArray[6] = { 0 };
int num = 0;
int x;
do {
printf("\nHow many dice would you like to roll? Please enter here: ");
scanf_s("%d", &num);//user enters amount of dice they want to roll)
if (num < 1 || num > 6) {
printf("\n\nPlease enter a number between 1 and 6.\n\n");
}
} while (num < 1 || num > 6);
tossDie(diceArray);
//print dice roll numbers
for (x = 0; x < num; x ) {
printf("%d ", diceArray[x]);
}
return 0;
}
void tossDie(int numbers[]){
int randomNum;
int x;
srand(time(NULL));
randomNum = (rand() % 6) 1; //random # between 1 - 6
for (x = 0; x < 6; x ){
numbers[x] = randomNum;
x ;
}
};
uj5u.com熱心網友回復:
移動
srand(time(NULL));到main()。只需要一次。僅在
x每個回圈中呼叫,而不是兩次,以分配陣列的所有 6 個元素。移動
randomNum = (rand() % 6) 1;到內部for回圈以獲得不同的值。scanf_s("%d", &num);在使用之前檢查 1 的回傳值num。
提示:使用自動格式化程式可以節省時間并改進代碼呈現。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327454.html
上一篇:陣列的動態索引
