Sunday, October 24, 2021

[SOLVED] Why does C not calculate the modulus correctly and despite this the result is correct?

Issue

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

Solution

    a = rand() % MAX_NUMBERS;
    vettore[i] = a;
    printf("vettore[%d] = %d - %d\n", i, a, rand());

You are calling rand() twice in the body of this loop. The call in printf() will not give you the same value that was used to calculate a.

If you want to verify the results of %, assign rand() to another temporary variable first. (But I doubt very much that this is your problem.)



Answered By - user149341