Why does this code produce the number 1? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Why does this code produce the number 1?

Panasonic99Panasonic99 Posts: 140Member
#include
#include
#include

void main()
{
int seed, secretnum1, secretnum2;
seed = time(NULL);
srand(seed);

secretnum1 = rand() % 1 + 21;
secretnum2 = rand() % 1 + 10;
printf("%d
", secretnum1 % secretnum2);
}


it keeps on producing 1...why?

Comments

  • pseudocoderpseudocoder Posts: 687Member ✭✭✭
    a number % 1 will return 0 since there is no remainder; you're getting the same results every time the program executes

    n1 = rand() % 1 + 21 or n1 = 21
    n2 = rand() % 1 + 10 or n2 = 10

    21 % 10 has a remainder of 1
    [code]
    2
    -----
    10 | 21
    - 20
    ---
    1
    [/code]
    : #include
    : #include
    : #include
    :
    : void main()
    : {
    : int seed, secretnum1, secretnum2;
    : seed = time(NULL);
    : srand(seed);
    :
    : secretnum1 = rand() % 1 + 21;
    : secretnum2 = rand() % 1 + 10;
    : printf("%d
    ", secretnum1 % secretnum2);
    : }
    :
    :
    : it keeps on producing 1...why?
    :
Sign In or Register to comment.