C - rand() 模 0

C - rand() modulo 0

当我尝试通过 int 生成随机数 0 时:

//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");
}

maximum[i][j] 为 0 时出现浮点异常。

有没有更好的方法来创建一个没有由 rand() % 0 引起的 floating point error 的随机数?

编辑: 当最大值为0时,随机数输出应该正好为0。

尝试改用它

//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");
}

你说:

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

您可以添加一张支票来解决这个问题。

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

您可以使用 ?: 运算符来整齐地编写该额外条件:

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

a % b 得到 a 除以 b 的余数。因此,它总是会给你一个小于 b 的结果,并且当 b 为零时它不起作用,因为你不能除以零。

如果想要0到x之间的随机数,需要取rand() % (x + 1).

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

模运算符是除法后的余数。由于除以零是未定义的,因此模 0 也是未定义的。

您需要一个条件来防止尝试除以零。您可以使用 if/else 语句或 ternary operator (?:) 来实现。换句话说,改变这个

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

以下之一。

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

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