我的學校專案讓我用用戶輸入的面數和擲數(分別在 1 到 25 和 1 到 500 之間)撰寫一個骰子。我的代碼應該能夠計算出現的次數以及百分比并列印出來。我想出了一些辦法,但我一直堅持對出現位進行編碼。我知道我應該使用陣列和回圈,但我認為我的實作是錯誤的。任何幫助將不勝感激。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int i;
int rollDice;
int diceFace[25] = {0};
int diceThrows[500] = {0};
srand(time(NULL));
printf("Number of faces: ");
scanf("%d", &diceFace);
if (diceFace > 1 && diceFace < 25)
printf("Range is acceptable");
else
printf("Range is unacceptable");
printf("\nNumber of throws: ");
scanf("%d", &diceThrows);
if (diceThrows > 1 && diceThrows < 500)
printf("Range is acceptable\n");
else
printf("Range is unacceptable");
for (i = 0; i < ; i )
{
diceThrows[i] = (rand() % diceFace 1);
diceFace[diceThrows[i]-1] ;
printf("%d \n", diceThrows[i]);
} for (i = 0; i < diceFace; i )
{
printf("The value [%d] was rolled %d times.\n", i 1, diceFace[i]);
}
這是我到目前為止得到的。陣列似乎不起作用。我知道我應該為拋出和伴隨的面孔撰寫一個陣列和一個回圈,并計算每個數字的出現次數。問題在于,在動態集合中執行此操作會使問題變得復雜。
uj5u.com熱心網友回復:
您在這里混淆了一些要求。據我所知(在您的示例中填寫一些空白),陣列diceThrows和diceFace應該分別包含擲骰子的順序和每次擲骰的頻率。
因此,
scanf("%d", &diceFace);
和
scanf("%d", &diceThrows);
沒有多大意義,因為他們試圖讀取單個int,但被賦予陣列地址作為寫入資料的位置。
您需要兩個獨立于陣列的其他變數來保存用戶輸入的值。
這里使用的 1和- 1
diceThrows[i] = (rand() % diceFace 1);
diceFace[diceThrows[i]-1] ;
不需要。
如果您的骰子有 16 個面,那么這些面的編號為 0 到 15。通過僅在向用戶顯示此資料時添加一個來進行調整。
scanf如果失敗或輸入的值超出可接受的范圍,您的程式不應繼續。這樣做會使您的程式在嘗試使用未初始化或不正確的資料時容易受到更多未定義行為的影響。
重構:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_FACES 25
#define MAX_THROWS 500
int get_int_in_range(int low, int high)
{
int n;
if ((1 != scanf("%d", &n)) || low > n || n > high) {
fprintf(stderr, "Value is unacceptable.\n");
exit(EXIT_FAILURE);
}
puts("Value is acceptable.");
return n;
}
int main(void)
{
srand((unsigned) time(NULL));
printf("Number of faces: ");
int faces = get_int_in_range(1, MAX_FACES);
printf("Number of throws: ");
int throws = get_int_in_range(1, MAX_THROWS);
int frequency[MAX_FACES] = { 0 };
int sequence[MAX_THROWS] = { 0 };
printf("The sequence of throws is: ");
for (int i = 0; i < throws; i ) {
int result = rand() % faces;
frequency[result] ;
/* save the sequence, not completely necessary */
sequence[i] = result;
/* since we can print as we go */
printf("%d ", result 1);
}
putchar('\n');
for (int i = 0; i < faces; i )
printf("The value [%d] was rolled %d times (%.2lf%%).\n",
i 1, frequency[i], (frequency[i] / (double) throws) * 100.0);
}
使用這個程式:
$ ./a.out
Number of faces: 6
Value is acceptable.
Number of throws: 10
Value is acceptable.
The sequence of throws is: 5 6 5 6 6 4 2 2 1 6
The value [1] was rolled 1 times (10.00%).
The value [2] was rolled 2 times (20.00%).
The value [3] was rolled 0 times (0.00%).
The value [4] was rolled 1 times (10.00%).
The value [5] was rolled 2 times (20.00%).
The value [6] was rolled 4 times (40.00%).
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534281.html
標籤:数组C循环动态的骰子
