Notices
Results 1 to 36 of 36
Like Tree6Likes
  • 1 Post By Strange
  • 2 Post By shlunka
  • 1 Post By RedPanda
  • 1 Post By Strange
  • 1 Post By river_rat

Thread: Why is the C++ random number not generated?

  1. #1 Why is the C++ random number not generated? 
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    #include <iostream>#include <stdlib.h>
    using namespace std;
    void main (void) {
    int a, b, c;
    cout << "Put in your number";
    a = rand() % 10 + 1;
    cin >> b;
    c = a + b;
    cout << c;
    system ("pause");
    }
    this is my code.
    i am supposed to key in a number, and then a random number will be added to it, and the answer will be shown in the next line.

    What happened, is that the random number is always generated to be 2,
    when i type 1, the final answer is 3, when i type 0, the final answer is 2, when i type 10, then final answer is 12.
    it doesn't work i dont know why.. i hope someone can answer. it be a great help!


    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  2.  
     

  3. #2  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    The rand() function always returns the same sequence of values (for a given seed). So if you only call it once, you will always get the same number. If you call it multiple times in your program you will get a (pseudo) random sequence of numbers.

    If you want to generate a different sequence every time, then you will need to initialise it with a different seed. A common way of doing this is using the time: rand - C++ Reference


    Surabhi likes this.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  4. #3  
    Forum Freshman
    Join Date
    Apr 2013
    Posts
    9
    Ok,
    That is good share. I was not aware about the concept. Though I like to do programming but in C and C++ but each of my concept like these are not clear.
    Reply With Quote  
     

  5. #4  
    Malignant Pimple shlunka's Avatar
    Join Date
    Jan 2013
    Location
    Dogbox in front of Dywyddyr's house.
    Posts
    1,784
    You're so silly Ryan, C isn't a number.
    RedPanda and RamenNoodles like this.
    "MODERATOR NOTE : We don't entertain trolls here, not even in the trash can. Banned." -Markus Hanke
    Reply With Quote  
     

  6. #5  
    Forum Masters Degree
    Join Date
    Jan 2011
    Posts
    738
    If I recall correctly, the older C compiler's random number function (between a min and max) always returned the same random numbers.
    Reply With Quote  
     

  7. #6  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by PumaMan View Post
    If I recall correctly, the older C compiler's random number function (between a min and max) always returned the same random numbers.
    I think it is defined that way. Deterministic behaviour, even for a "random" number generator, is important for some applications.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  8. #7  
    has lost interest seagypsy's Avatar
    Join Date
    Nov 2012
    Posts
    3,107
    looking in my c++ text book, it says that you should write it as
    a = 1+ rand() % 10;

    I can't for the life of me figure out why putting the equation in this order matters but maybe it does.
    Reply With Quote  
     

  9. #8  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    how do i make a script that jumps to a specific line if i enter 5 into the console?
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  10. #9  
    has lost interest seagypsy's Avatar
    Join Date
    Nov 2012
    Posts
    3,107
    sorry for late reply. do you know how to write functions yet? you could do an if statement

    something like

    if (input == 5){
    functionName();

    else
    other instructions;

    And somewhere else in the code you will want to right the function definition

    but you will want to double check the syntax. I have learned several languages in the past year and I sometimes get them mixed up.

    I also don't have my textbooks on c++ handy. I'm in the hospital right now.
    Reply With Quote  
     

  11. #10  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    this is my code for a game, and i have a problem here...
    when it goes to the point where it says "The game I want to play is ", and i type a letter in the alphabet, e.g."hello", it screws up and "invalid character." keeps spamming.

    i know "hello" cant be stored in an integer variable. but my project requires me to use integer variables.
    how do i solve this issue, to check if its a integer value before storing it in the integer variable?
    Last edited by RamenNoodles; May 23rd, 2013 at 12:10 AM.
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  12. #11  
    has lost interest seagypsy's Avatar
    Join Date
    Nov 2012
    Posts
    3,107
    well you can either use enumerated variables or you can do a switch case. But do you know how to create and use functions yet?

    its also good practice to make your variables a little less mysterious.

    I mean rather than just unintelligible letters to decipher... say, if you want to use a variable to hold the number of eggs in a carton, you may call it numEggs rather than e or ne

    if you make your variables a little more obvious it will be easier for you to debug later on. and easier for those helping you figure out what you are doing.
    Reply With Quote  
     

  13. #12  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by seagypsy View Post
    its also good practice to make your variables a little less mysterious.
    Excellent advice.

    It would also be useful if you (ryanawe123) put you code inside [code][/code]tags. It would make it a bit easier to read.

    Are you using a book to learn from? It would be a good idea to follow some sort of structured course of study initially.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  14. #13  
    has lost interest seagypsy's Avatar
    Join Date
    Nov 2012
    Posts
    3,107
    Quote Originally Posted by Strange View Post
    Quote Originally Posted by seagypsy View Post
    its also good practice to make your variables a little less mysterious.
    Excellent advice.

    It would also be useful if you (ryanawe123) put you code inside [code][/code]tags. It would make it a bit easier to read.

    Are you using a book to learn from? It would be a good idea to follow some sort of structured course of study initially.
    @Strange.

    I am new to programming myself and still have to go back to my text books for almost everything. anything that is beyond beginner basics will be beyond me. So any correction you can give me while helping ryanawe123 can help us both.
    Reply With Quote  
     

  15. #14  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by seagypsy View Post
    @Strange.

    I am new to programming myself and still have to go back to my text books for almost everything. anything that is beyond beginner basics will be beyond me. So any correction you can give me while helping ryanawe123 can help us both.
    I'd be happy to help, where I can. So maybe I should go back to this point:
    Quote Originally Posted by seagypsy View Post
    looking in my c++ text book, it says that you should write it as
    a = 1+ rand() % 10;

    I can't for the life of me figure out why putting the equation in this order matters but maybe it does.
    In this case it doesn't matter. The order in which the expression is evaluated depends on two things: the precedence of the operators (+ * % etc) and, where two operators have the same precedence, the order in which they are written.

    In this case, % has a higher precedence than + and so the modulus will be calculated first and then the addition, regardless of the order they are written.

    In the case of two operators with the same precedence (such as multiplication and modules) then the order in the expression is significant. For example: a * b % c may give a different result than b % c * a. The order in which the expression is evaluated then depends on the associativity of the operators (i.e. do the "bind" to the left or right).

    Because this can be rather non-obvious, I always use parentheses to control / describe the order of evaluation if there is any possibility of confusion (by either me or another reader of the code). It is good code documentation practice as much as good coding.

    So, although I might be happy to write 1 + rand() % 10, I would always write either (5 * rand()) % 10 or 5 * (rand() % 10) to make it clear (to myself and others, exactly what I meant) rather than rely just on ordering. I know there are programmers who think that is unnecessary but it costs nothing and can avoid problems.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  16. #15  
    ▼▼ dn ʎɐʍ sıɥʇ ▼▼ RedPanda's Avatar
    Join Date
    Aug 2012
    Location
    UK
    Posts
    2,737
    Quote Originally Posted by Strange View Post
    So, although I might be happy to write 1 + rand() % 10, I would always write either (5 * rand()) % 10 or 5 * (rand() % 10) to make it clear (to myself and others, exactly what I meant) rather than rely just on ordering. I know there are programmers who think that is unnecessary but it costs nothing and can avoid problems.
    ...and as an additional programming tip, try to avoid Magic numbers
    (I realise that your example was simplified for educational purposes, but I thought it might be worth mentioning for those learning to code.)
    Strange likes this.
    SayBigWords.com/say/3FC

    "And, behold, I come quickly;" Revelation 22:12

    "Religions are like sausages. When you know how they are made, you no longer want them."
    Reply With Quote  
     

  17. #16  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    simply to put, how do i check if a "cin" number is an integer before storing it in the integer variable "g"?

    btw why do you think its confusing?

    e.g. "s iv b"
    s is subtraction question.
    iv is question four.
    b is the second value in the equation.

    confusing? doesn't seems to me

    so,

    simply to put, how do i check if a "cin" number is an integer before storing it in the integer variable "g"?
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  18. #17  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by ryanawe123 View Post
    simply to put, how do i check if a "cin" number is an integer before storing it in the integer variable "g"?
    I have never made much use of the stream io functions so I don't know if there is a better answer, but I would suggest reading it as a string then using one of the conversion functions, such as strtol - C++ Reference

    This will allow you to do error checking on the input.

    btw why do you think its confusing?

    e.g. "s iv b"
    s is subtraction question.
    iv is question four.
    b is the second value in the equation.
    You know that now (no one else does). Wait till you have to come back to some code you wrote a year ago. "What is 'iv'? Intravenous?"
    RamenNoodles likes this.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  19. #18  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    why does this thing have errors?
    Code:
    #include <iostream>
    
    
    using namespace std;
    
    
    void main (void) {
        int g;
    
    
        cin >> ("%d", &g);
    cout << (”input value is %d”, g);
    }
    what i want it to do is simply store the value if its a decimal, and show it. but the script doesnt work.
    Last edited by RamenNoodles; May 5th, 2013 at 10:33 AM. Reason: seagypsy, thats for spotting the mistake.. but it still wont work
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  20. #19  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by ryanawe123 View Post
    why does this thing have errors?
    I'm afraid I am not familiar enough with C++ stream io to comment. I don't even recognise the syntax of that code.

    It would be helpful if you explain what you mean by "have errors":

    Does it compile? If not what is the error message?
    Does it execute? If not, what is the error message?
    Do you get a run time error? If so, what is the error message?
    Do you get an unexpected result? If so, what?
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  21. #20  
    has lost interest seagypsy's Avatar
    Join Date
    Nov 2012
    Posts
    3,107
    I've never seen colons used the way you used them here.

    I've always seen it used like this

    cin <<

    cout>>

    printf<<

    which IDE are you using?
    Reply With Quote  
     

  22. #21  
    New Member
    Join Date
    May 2013
    Posts
    3
    Hello,
    To generate random sequence , you should initialize rand() fn with deferent seed. Write a function that accepts seed and intialize the rand fn.
    Last edited by gerrywilson; May 7th, 2013 at 06:46 AM.
    Reply With Quote  
     

  23. #22  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    Okay, i finally solved the problem with random number generator!

    but now im having a small problem of understanding why something is used.


    i removed the 1000, and it doesnt work problerly, quite glitchy... hard to describe what happens, when entering, it sometimes gone to a new line and sometimes the error check works properly....................

    anyway, can someone kindly tell me whats that 1000 for? i dont quite get it.
    Last edited by RamenNoodles; May 23rd, 2013 at 12:11 AM.
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  24. #23  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  25. #24  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    ok. i read it, its to ignore up to 1000 characters until /n command is given.

    but how do i make it to ignore infinity characters until /n command is given?
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  26. #25  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    i know number infinity cant be possible with binary system,

    or something like:
    "ignore all characters until the command /n is given"
    ?

    help thx
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  27. #26  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Sounds like you need your own function, something like:
    Code:
    char c;
    do c = cin.get() while (c != '\n') && (c != EOF);
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  28. #27  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    But if i want to do string is is possible?
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  29. #28  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    You need to explain what you want to do. The ignore() function just discards characters up the newline '\n'; as does my code fragment. What do you want to do with a string? Is the getline() or one of the get() functions more appropriate?
    istream::getline - C++ Reference
    istream::get - C++ Reference
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  30. #29  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    this is the problem (stated in the '//' comment)
    Code:
    while ( ! (cin >> integervariable)) {//Invalid Response
            cout << "This is not an integer, please enter an integer, thankyou. input: ";
            cin.clear ();
                  cin.ignore(256,'\n'); //<---------------------- this is the part. (256,'\n'); is to ignore 256characters, or until the '\n' (next line command) is given
    but what i want to do is to ignore any number of characters until the command '\n' is given, even if cin is 1000characters long, or 10000000characters long.
    is there a way to do it, rather than using:
    Code:
    cin.ignore(A_Really_Huge_Number,'\n');
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  31. #30  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by ryanawe123 View Post
    but what i want to do is to ignore any number of characters until the command '\n' is given, even if cin is 1000characters long, or 10000000characters long.
    is there a way to do it, rather than using:
    Code:
    cin.ignore(A_Really_Huge_Number,'\n');
    So I don't see why my suggestion in post #26 does not meet your needs?

    Alternatively, according to the standard, the following is defined not to count characters but only terminate when the specified character is found. Which is exactly what you want.
    Code:
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  32. #31  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    then if i have thousands of integer variables, and i want to write a generic code to check for all the int variables, how do i go about it, rather than listing them one by one?



    while ( ! (cin >> //AllMyIntVariables))
    for all the int variables, rather than listing them one by one?



    sorry quite new to programmg


    ohh.. and i want to check for all INT inputs, its its not a whole number, it will also ignore it.



    EDIT:
    because i have tons of variables...
    and i want to save time and space by just making one section to check for all the cin into all my int vars.
    Last edited by RamenNoodles; May 8th, 2013 at 07:48 PM.
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  33. #32  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Do you mean you have a large number of integer variables that you want to initialise by inputting the values? Is the input going to be entered from the keyboard? Or a file?

    Without not knowing more about what you are doing, one way of reading a series of values is to read them into an array. Then you can write a loop to read all the values:
    Code:
    #define N 100
    
    int many_int_vars[N];
    
    for (int i=0; i < N; i++) {
        cin >> many_int_vars[i];
        // insert error checking code here
    }
    But that is really only a good idea if you always want to treat that array of variables in the same way.

    You could do a similar thing with other data structures.
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  34. #33  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    Oh thanks ALOT!

    i didnt think of using an array how silly of me

    now using an array its really awesomely easy to check.

    but i have a question: if i make the function to check for myarray[5], does it check the fifth variable in the array or all varables from [1] to [5]?

    and also, what is
    Code:
    #define N 100
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

  35. #34  
    Brassica oleracea Strange's Avatar
    Join Date
    Oct 2011
    Location
    喫茶店
    Posts
    16,603
    Quote Originally Posted by ryanawe123 View Post
    but i have a question: if i make the function to check for myarray[5], does it check the fifth variable in the array or all varables from [1] to [5]?
    No, it will check that single lement of the array.

    and also, what is
    Code:
    #define N 100
    It is a way of avoiding "magic numbers" in your code. (Although I should have called it ARRAY_SIZE or NUMBER_OF_VARIABLES instead of N to make the meaning explicit.) If you want to change the size of the array (and the corresponding number of iterations of the loop) you can do it in one place, rather than changing a number in multiple places.

    And in C++ I suppose it would be preferred to use a const:
    const int ARRAY_SIZE = 100;
    Without wishing to overstate my case, everything in the observable universe definitely has its origins in Northamptonshire -- Alan Moore
    Reply With Quote  
     

  36. #35  
    Forum Professor river_rat's Avatar
    Join Date
    Jun 2006
    Location
    South Africa
    Posts
    1,497
    Just to add my own 2c - use std::vector templates instead of arrays, because arrays are evil!
    Strange likes this.
    As is often the case with technical subjects we are presented with an unfortunate choice: an explanation that is accurate but incomprehensible, or comprehensible but wrong.
    Reply With Quote  
     

  37. #36  
    Forum Ph.D.
    Join Date
    Jan 2013
    Posts
    911
    Hey, may i ask, can i case a variable or an expression in a switch function?

    (there may be errors, but i put this [.code] here to point out the case.
    Code:
    int myvariable = rand()%6;;
    int userans
    cout<< "guess a number from 1 to 5";
    cin>>userans
    /*person cins 4*/
    switch(userans){
    case !myvariable&&!>5: cout<<"loser"; break;
    case >5: cout<<"wtf?"; break;
    case myvariable: cout<<"win"; break;
    }
    instead of
    case 1:
    case 2:
    case 3:
    or
    case 'somewords':
    ......
    can variables or expressions be used in switches?
    how can i make variables or expressions to be able to be used in switches?
    Last edited by RamenNoodles; May 31st, 2013 at 01:49 PM.
    Quote Originally Posted by jocular View Post
    If thy right nipple offend thee, pluck it off! Goes for the other, too!
    Reply With Quote  
     

Similar Threads

  1. Help with random lotto number generator!
    By Rickz2020 in forum Computer Science
    Replies: 2
    Last Post: May 30th, 2011, 02:02 AM
  2. How are DNA nucleotides generated
    By gs99 in forum Biology
    Replies: 4
    Last Post: December 31st, 2009, 09:21 PM
Bookmarks
Bookmarks
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •