My code generates a random number between 1 and 6 for 1000 times and I need to count how many times each number appeared in percentage. My problem is that it is, sometimes, generating negative percentages and it is surpassing 100%. I also must use a switch
.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
int i, n, max = 6;
int num1, num2, num3, num4, num5, num6;
float total1, total2, total3, total4, total5, total6;
srand(time(NULL));
for (i = 0; i < 1000; i++) {
n = rand() % max + 1;
switch (n) {
case 1:
num1 += 1;
case 2:
num2 += 1;
case 3:
num3 += 1;
case 4:
num4 += 1;
case 5:
num5 += 1;
case 6:
num6 += 1;
}
}
total1 = num1 / 100;
printf("Times 1 appeared: %f\n", total1);
total2 = num2 / 100;
printf("Times 2 appeared: %f\n", total2);
total3 = num3 / 100;
printf("Times 3 appeared: %f\n", total3);
total4 = num4 / 100;
printf("Times 4 appeared: %f\n", total4);
total5 = num5 / 100;
printf("Times 5 appeared: %f\n", total5);
total6 = num6 / 100;
printf("Times 6 appeared: %f\n", total6);
}