结果获得“30”的机会非常小。您也不会得到从 1 到 9 的随机数,而是从 0 到 9 得到它们。
试试这个:
int numone,numtwo,numthree,numfour, finalsum;
do
{
do
{
numone = 1+rand()%9;
numtwo = 1+rand()%9;
} while (numone+numtwo < 12);
numthree = 1+rand()%9;
} while (numone+numtwo+numthree < 21);
numfour = 30-(numone+numtwo+numthree);
// for clarity
finalsum = numone + numtwo + numthree + numfour;
(编辑)经过一些横向思考:numthree
需要介于30-1-(numone+numtwo)
和30-9-(numone+numtwo)
之间——也许那里还有进一步优化的空间。
(进一步编辑)经过下面的审议,我实际测试了它,确实,这符合要求:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int main (void)
{
int numone,numtwo,numthree,numfour, finalsum;
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
numone = 3+rand()%7;
if (numone == 3)
numtwo = 9;
else
numtwo = 12-numone+rand()%(7-(9-numone));
if (numone + numtwo == 12)
numthree = 9;
else
numthree = 21-(numone+numtwo)+rand()%(6-(18-(numone+numtwo)));
numfour = 30 - (numone + numtwo + numthree);
finalsum = numone + numtwo + numthree + numfour;
printf ("%d + %d + %d + %d = %d\n", numone, numtwo, numthree, numfour, finalsum);
}
}