如何将输出输入到c中的数组中

  • 本文关键字:数组 输出 c
  • 更新时间 :
  • 英文 :


到目前为止我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main()
{
int i;
int rollDice;
int firInp;
int secInp;
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): ");
scanf("%d", &firInp);
printf("Enter the amount of throws you want(MAX=499, MIN=1): ");
scanf("%d", &secInp);
srand ( time(NULL) );
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1;
printf("%d n", rollDice);
}
}
else{
printf("Sorry, these numbers don't meet the parameters. Please enter a number in the right parameters.");
}
return 0;
}

我想在代码中包含百分比。我认为这样做的方法是首先将代码的输出输入到一个数组中。如果有其他方式,请随时告诉我。

编辑:我希望输出像这样:

1 3 4 4 5发生率为1:16.6%出现3:。。等等

不必在数组中输入随机函数的输出,只需将该数组用作计数器,并在每次出现数字时在rollDice位置递增数组。然后,您可以通过对数组的所有元素求和,并将每个元素除以该和,轻松地提取百分比。

您可以创建一个整数数组,其大小等于骰子可以输出的可能值的数量。然后,您将其用作发生次数的计数器,数组的索引将表示该输出值(您可以使用rollDice-1,因为0不是骰子的可能输出(,索引处的值将是发生次数。在你完成掷骰子后,你只需要打印这样的百分比:

for (int i=0;i<firInp;i++) { // firInp: n_faces = n_possible_values
printf("Occurrence of %d: %.1f percentn", i+1, ((float)array[i]*100)/(float)secInp);
}