NewCoder2001
NewCoder2001

Reputation: 3

How to enter an output into an array in c

My Code so far:

#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;
}

I want to have percentages in my code. I think the way to do that is to first enter the output of my code into an array. If there's another way please feel free to let me know.

edit: I want the output to be something like this:

1 3 4 4 4 5 occurrence of 1: 16.6 percent occurrence of 3: ..and so on

Upvotes: 0

Views: 109

Answers (2)

Matteo Pinna
Matteo Pinna

Reputation: 409

You can create an array of integers, with size equals to the numbers of possible values your dice can output. Then you use it as a counter for the number of occurences you get, the index of the array will represent that output value (you can use rollDice-1 since 0 isn't a possible output of the dice), and the value at the index will be the number of occurences. After you finish rolling the dice you just have to print the percentage like this:

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

Upvotes: 0

Giovanni Zaccaria
Giovanni Zaccaria

Reputation: 371

Instead of entering the output of the random function in an array you could just use that array as a counter, and incrementing the array at position rollDice every time a number appears. Than you could easily extract the percentage by summing all the elements of the array and by dividing each element by that sum.

Upvotes: 2

Related Questions