1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Need Help

Discussion in 'C++' started by ikusung, Mar 12, 2010.

  1. ikusung

    ikusung New Member

    Joined:
    Mar 12, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    #include <iostream>
    #include <time.h>
    using namespace std;
    void main() {
    srand(time(0));
    while (true) {
    int brian;
    int happy;
    int r;
    r = rand () %101;
    cout <<rand () %101 << "\n";
    cout << "enter number \n" ;
    cin >> brian;
    if (brian == r) {
    cout << "Go you, you win\n";
    }
    else if (r<brian){
    cout << "Lower\n";
    }
    else {
    cout << "Higher\n";
    }
    }
    }

    Could anyone point out what's wrong with my code .
    It's meant to be a higher or lower game but it keeps generating a new number everytime?
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    If you format the code correctly the problem should be obvious:
    Code:
    #include <iostream>
    #include <time.h>
    using namespace std;
    void main() {
    	srand(time(0));
    	while (true) {
    		int brian;
    		int happy;
    		int r;
    		r = rand () %101;
    		cout <<rand () %101 << "\n";
    		cout << "enter number \n" ;
    		cin >> brian;
    		if (brian == r) {
    			cout << "Go you, you win\n";
    		}
    		else if (r<brian){
    			cout << "Lower\n";
    		}
    		else {
    			cout << "Higher\n";
    		}
    	}
    }
    
    If you don't want a new number on every iteration, why is
    Code:
    r = rand () %101;
    
    inside the while loop?
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    By the way, rand() returns a new random number each time it is called, so
    Code:
    cout <<rand () %101 << "\n";
    
    would not be expected to display r. If you want it to display r, you have to tell it to display r.
     

Share This Page