您好,我已經編寫了基於rand()和time.h的骰子滾動生成器所需的代碼。 它基本上要求用戶輸入他希望擲骰子的次數,然後將這些擲骰X次。它將1-6數字中的每個數字在數組中滾動的次數以及每個數字在另一個數組中的百分比保存起來。滾動骰子直方圖
現在我想要做的是創建一個直方圖的數字1-6和 - 在X軸上的百分比和|在Y軸和星號(*)爲列。
事情是這樣的:
10% | *
8% |* * *
6% |* * * * *
4% |* * * * * *
2% |* * * * * *
+------------
1 2 3 4 5 6
我有搜索throught谷歌找到的東西開始,但我確實發現了類似我的情況下,多數民衆贊成什麼會幫助我開始。
我的代碼從而爲是:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random_number();
float calc_percentage(int totals, int nums);
float calc_maxper(float perc[6]);
float calc_minper(float perc[6]);
float permin;
float permax;
int main(void)
{
int nums;
int i;
int totals[6] = {0};
float percentages[6] = {0};
srand(time(NULL));
printf("How many numbers to generate?");
scanf("%d", &nums);
for (i = 1; i <= nums; i++)
{
int x = random_number();
totals[x-1]++;
}
for (i = 0; i<6; i++)
{
percentages[i] = calc_percentage(totals[i],nums);
printf("The percentage of each number is: %.2f%\n", percentages[i]);
}
permin = calc_minper(percentages);
permax = calc_maxper(percentages);
if (((permax) - (permin)) > 5)
printf("The generator is not good.\n");
printf("The percentage difference is:%.1f\n", permax-permin);
system("pause");
return 0;
}
int random_number()
{
int randnum;
randnum = 1 + (rand() % 6);
return randnum;
}
float calc_percentage(int totals, int numbers)
{
float a;
a = (totals * 100)/numbers;
return a;
}
float calc_minper(float perc[6])
{
int i;
float min;
min = perc[0];
for (i=1; i<6; i++)
{
if (perc[i] < min)
min = perc[i];
}
return min;
}
float calc_maxper(float perc[6])
{
int i;
float max;
max = perc[0];
for (i=1; i<6; i++)
{
if (perc[i] > max)
max = perc[i];
}
return max;
}
好吧,我終於得到了這個工作。
有點長和凌亂,但它絕對得到完成的工作!
printf("20%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 20)
printf("* ");
}
printf("\n");
printf("16%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 16)
printf("* ");
}
printf("\n");
printf("12%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 12)
printf("* ");
}
printf("\n");
printf(" 8%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 8)
printf("* ");
}
printf("\n");
printf(" 4%|");
for (i=0; i<6; i++)
{
if (percentages[i] >= 4)
printf("* ");
}
printf("\n");
printf(" +------------\n");
printf(" 1 2 3 4 5 6\n");
感謝您的創意花花公子! 如果你有任何快速的想法,讓它變得更短!
正是你從哪裏得到stucked?順便說一句:作業? – Matthias 2012-04-16 19:32:34
而不是調試你的整個代碼,你可以指導我們 - 當前解決方案的問題是什麼,當前的輸出是什麼等等? – 2012-04-16 19:33:08
您的calc_percentage函數返回一個int轉換爲float值。通過使用100.0而不是100來強制執行浮點操作。 – Spidey 2012-04-16 19:40:22