jeudi 26 septembre 2019

Why does C not calculate the module correctly and despite this the result is correct?

I'm learning to use the random function (srand and rand) to run a dice roll simulation. The program works very well; I throw the dice 200 times and I put each result into the vettore array.

However, analyzing the calculation of the rest of the module I realized that it is not calculated correctly. For example:

1131946436 % 6 = 2 

(calculated by hand and with python and with a calculator).

the module is calculated as follows:

1131946436 / 6 = (int) 188657739
188657739 * 6 = 1131946434
1131946436 - 1131946434 = 2

while C gives me 3.

Nevertheless the program works correctly. I thought it was an int overflow problem but if you look at the results of rand() we are always under 2147483647 (the int signed limit on my 64 bit computer).

I can't understand why C doesn't calculate the module correctly and despite this the program works correctly.

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

#define MAX_SHOTS 200
#define MAX_NUMBERS 6

int main(void) {
    int a;
    int vettore[MAX_SHOTS] = {0};

    srand((unsigned) time(NULL));

    for (int i = 0; i < MAX_SHOTS; ++i) {
        a = rand() % MAX_NUMBERS;
        vettore[i] = a;
        printf("vettore[%d] = %d - %d\n", i, a, rand());
    }

    printf("Tiro di un dado: su %d tiri è uscito:\n", MAX_SHOTS);
    for (int j = 0; j < MAX_NUMBERS; ++j) {
        printf("%d)\t", j + 1);
        int num = 0;
        for (int i = 0; i < MAX_SHOTS; ++i) {
            if (vettore[i] == j) {
                ++num;
                printf("*");
            }
        }
        printf(" (%d)\n", num);
    }

    return 0;
}



Aucun commentaire:

Enregistrer un commentaire