【问题标题】:Rolling 2 dice desirable amount of time and print out percentages滚动 2 个骰子所需的时间并打印出百分比
【发布时间】:2013-12-29 19:55:47
【问题描述】:

我的任务是执行一个程序,该程序将 2 个骰子掷出 x 次,然后打印出每个数字 (2-12) 的结果。这就是我已经走了多远,但正如你所见,我被困住了。我不知道如何将数组从 throw_dice 函数获取到 print_result 函数。我也不知道如何计算和打印出每个数字的实际百分比。我不是要求有人为我完成代码,而是一些提示!

提前谢谢。

#include <stdio.h>
#include <time.h>

int array[11];
int count=0;

int get_no_of_throws()
{
    int throws;
    printf("How many throws? ");
    scanf("%i", &throws);
    return throws;
}

int throw_dice(int throws)
{
    int dice1;
    int dice2;
    int sum=0;
    srand(time(NULL));
    for(count=0;count<11;count++)
    {
        array[count]=0;
    }
    for(count=0;count<throws; count++)
    {
        dice1=rand()%6+1;
        dice2=rand()%6+1;
        sum=dice1+dice2;
        ++array[count];
    }
    return array[count];
}

void print_results(array)
{
    ?????
}

int main()
{
    int throws;
    get_no_of_throws();
    throw_dice(throws);
    print_results(array);
    return 0;
}

【问题讨论】:

  • 如果您将这个“C”标记为“C”,您将收到 很多 条评论 - 可能太多了。

标签: arrays function dice


【解决方案1】:

使用总和作为数组索引。

dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
sum = dice1 + dice2;
array[sum-2]++;

要打印,循环遍历数组并...

printf("%d %0.1f%%\m", count + 2, array[count]*100.0/throws);

很高兴考虑添加:打印预期结果的百分比。也可以在某处打印throws

检查输入结果并确保返回已知值。如果用户输入“ABC”,当前代码返回垃圾。考虑fgets()/sscanf()

if (1 != scanf("%i", &throws)) ComplainToUserAboutInput();

return array[count]; 不好。简单返回 0 或让函数返回void

int count=0; 从全局范围移入函数范围。我会将array 从全局移至main(),然后将其传递给各种函数。顺便说一句:考虑为array 取另一个名称,例如 dice_occurrence[]。比“数组”更具描述性。

// int count=0;

int throw_dice(int throws) {
  int count;
  ...
  for(count=0; count<11; count++) 
    ...
  for(count=0; count<throws; count++)
    ...
}

次要:考虑使变量更本地化,如

// int dice1;
// int dice2;
// int sum=0;
... 
for(count=0;count<throws; count++)  {
    int dice1 = rand()%6 + 1;
    int dice2 = rand()%6 + 1;
    int sum = dice1 + dice2;
    array[sum-2]++;
}

让空格字符成为你的朋友。

// dice1=rand()%6+1;
dice1 = rand()%6 + 1;

srand(time(NULL)); 适合生产。您可能需要在调试期间注释掉以获得可重复的结果。

其他可能的简化或功能。对我来说,我会创建一个 6x6 数组,然后只做dice[rand()%6][rand()%6]++;,然后将像 dice[2][1] 和 dice[1][2] 这样的对加起来。人们还可以评估诸如 dice[2][1] 和 dice[1][2] 彼此之间的接近程度等。

祝你好运。

【讨论】:

  • 谢谢。我会在我的代码中改变它,并继续思考我应该做些什么来修复它!
  • 哇,你真的花了一些时间和心思帮助我,真的很感激!!
  • @Jullebaloo 欢迎来到 SO。避免感谢相反,对有用的答案进行投票(一旦获得 15+ 代表)。一段时间后(几小时到几天),如果某个答案很好地满足了您的需求,请接受最好的答案。
猜你喜欢
  • 1970-01-01
  • 2021-05-16
  • 2016-09-17
  • 1970-01-01
  • 2021-08-28
  • 2019-10-24
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多