Sean
Sean

Reputation: 1313

C - rand() modulo 0

When I am trying to generate a random number 0 through int:

//Populate Currently Allocated Reasource for each customer
for (i = 0; i < NUMBER_OF_CUSTOMERS; i++) 
{
    printf("%d:[ ",i);
    for (j = 0; j < NUMBER_OF_RESOURCES; j++)
    {
        allocation[i][j] = rand() % maximum[i][j];
        printf("%d ",allocation[i][j]);
    }
    printf("] \n\n");
}

I get a floating point exception when maximum[i][j] is 0.

Are there any better means of creating a random number without the floating point error caused by rand() % 0?

EDIT: When maximum is 0, the random number output should just be 0.

Upvotes: 2

Views: 853

Answers (5)

cp.engr
cp.engr

Reputation: 2489

When maximum is 0, the random number output should just be 0.

The modulo operator is the remainder after a division. Since division by zero is undefined, so is modulo 0.

You need a condition to prevent attempting to divide by zero. You can do that with if/else statements, or the ternary operator (?:). In other words, change this

allocation[i][j] = rand() % maximum[i][j];

to one of the following.

if (maximum[i][j] == 0)
{
    allocation[i][j] = 0;
}
else
{
    allocation[i][j] = (rand() % maximum[i][j]);
}

or

allocation[i][j] = (maximum[i][j] == 0) ? (rand() % maximum[i][j]) : 0;

Upvotes: 0

anon
anon

Reputation:

You can use the ?: operator to write that extra condition neatly:

allocation[i][j] = maximum[i][j] ? (rand() % maximum[i][j]) : 0;

?: Conditional Expression: If Condition is true ? Then value X : Otherwise value Y


In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.

Wikipedia

Upvotes: 0

user149341
user149341

Reputation:

Taking a % b gives you the remainder when a is divided by b. As such, it will always give you a result that is less than b, and it doesn't work when b is zero, because you can't divide by zero.

If you want a random number between 0 and x, you need to take rand() % (x + 1).

Upvotes: 2

R Sahu
R Sahu

Reputation: 206707

You said:

When maximum is 0, the random number output should just be 0.

You can add a check to take care of this.

if ( maximum[i][j] == 0 )
{
   allocation[i][j] = 0;
}
else
{
   allocation[i][j] = rand() % maximum[i][j];
}

Upvotes: 0

Mykola
Mykola

Reputation: 3373

Try to use this instead

//Populate Currently Allocated Reasource for each customer
for (i = 0; i < NUMBER_OF_CUSTOMERS; i++) 
{
    printf("%d:[ ",i);
    for (j = 0; j < NUMBER_OF_RESOURCES; j++)
    {
        allocation[i][j] = maximum[i][j] ? (rand() % maximum[i][j]) : 0;
        printf("%d ",allocation[i][j]);
    }
    printf("] \n\n");
}

Upvotes: 1

Related Questions