C++ multiple random numbers adding up to equal a certain number

后端 未结 3 1135
时光取名叫无心
时光取名叫无心 2021-01-29 08:15

Having a little trouble figuring this one out, I have a bunch of int variables which are generating random numbers from 1-9. I need them to generate the correct numbers to equal

3条回答
  •  逝去的感伤
    2021-01-29 09:10

    The chance that you get '30' for a result is pretty small. You also don't get a random number from 1 to 9, you get them from 0 to 9.

    Try this instead:

    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;
    

    (Edit) After some lateral thinking: numthree needs to be between 30-1-(numone+numtwo) and 30-9-(numone+numtwo) -- perhaps there is room for a small further optimization there.

    (Further edit) After the deliberations below I actually tested it, and indeed, this works per requirement:

    #include 
    #include 
    #include 
    
    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);
      }
    }
    

提交回复
热议问题