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

后端 未结 3 1086
时光取名叫无心
时光取名叫无心 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 08:49

    Move the rand() into the while loop, or you'll generate random numbers only once, and get stucked in while loop.

    do{
    int numone = rand()%10;
    int numtwo = rand()%10;
    int numthree = rand()%10;
    int numfour = rand()%10;
    int finalsum;
    finalsum = numone + numtwo + numthree + numfour;
    }while(finalsum !=30);
    
    0 讨论(0)
  • 2021-01-29 08:55

    Well, i hope you realize that in your do while loop, you are not actually changing the values of the random numbers.What you are doing is basically checking the same condition of finalsum = numone + numtwo + numthree + numfour; infinitely if it does not equal 30.What you should do is:

    int numone,numtwo,numthree,numfour,finalsum;
    do{
    numone=rand()%10;
    numtwo=rand()%10;
    numthree=rand()%10;
    numfour=rand()%10;
    finalsum = numone + numtwo + numthree + numfour;
    }while(finalsum !=30);
    
    0 讨论(0)
  • 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 <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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题