logo elektroda
logo elektroda
X
logo elektroda

[C++] Create Random Integer Function within Custom Range (Example: 5 to 16)

qmpel 28202 4
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 1165076
    qmpel
    Level 16  
    Hey !!

    I have a request, could someone give me a function written in C / C ++ to generate an integer in the range, for example, from 5 to 16 ??

    Regards !!

    I close. - arnoldziq
  • ADVERTISEMENT
  • Helpful post
    #2 1165109
    wddf
    Level 18  
    Hi, I don't know what it is like in C, but for example in Pascal it is done like this:
    number: = random (16);

    it gives a random from 0 to 16, you can make a loop that eliminates smaller than 4, I think the toilet is very similar, you only need to find the equivalent of "random", good luck
  • ADVERTISEMENT
  • Helpful post
    #3 1165287
    Bielsky
    Level 21  
    
    #include 
    #include 
    int main(int argc, char *argv[])
    {
      int i;
      srand(time(0));
      // %12 bo zakres ma 12 liczb
      //5 bo najniższa to 5
      i = rand()%12 + 5;
      printf("%i\n",i);  
      system("PAUSE");	
      return 0;
    }
    
  • ADVERTISEMENT
  • Helpful post
    #4 1165310
    Paweł Es.
    VIP Meritorious for electroda.pl
    int x;
    
    x=5+(rand() % 12);


    General: generating integers in the range where b> a
    
    x=a+(rand() % (b-a+1)); // prosta metoda ale korzysta z małej ilości
                                          // bitów i liczby są "średnio" losowe.
    second method (better):

    x = a + int((b-a+1) * rand()/(RAND_MAX+1.0));
  • #5 1165403
    qmpel
    Level 16  
    Hey !!

    Thank you thank you thank you, !!

    Regards !!
ADVERTISEMENT