Hi there, well done for getting your function to work as you wanted :o) Now that it's working you could do a little tidying, since choose_number is a little more verbose than it could be. In fact, the whole thing only needs one line:
int choose_number( int option_a, int option_b )
{
return (rand() % 2 == 0) ? option_a : option_b;
}
Theternary operator ?: is very useful for this kind of situation and once you get used to it, I find that it makes code more readable :o)
If you want to go further, you could use afunction template here, so that you can get a choose_number for double , or std::string or indeed any class that you might want to create yourself:
template< typename T >
inline T choose_item( const T& item_1, const T& item_2 )
{
return (rand() % 2) ? item_1 : item_2;
}
With this template, now you get functions to do al these things for free:
class MyClass{
/* ... */
};
int main()
{
srand(time(0));
int door1 = 2;
int door2 = 5;
int eliminate_door = choose_item(door2, door3);
std::cout << eliminate_door << std::endl;
std::string someString( "Foo" );
std::string otherString( "Bar" );
std::cout << choose_item( someString, otherString ) << std::endl;
MyClass A, B;
MyClass C = choose_item( A, B );
return 0;
}
I'd also be annoyed by that pesky srand() hanging about in main() too. You can get rid of this by encapsulating it with the function that uses it in a class, let's call it RandomChooser :
struct RandomChooser{
RandomChooser(){ srand( 0 ); }
RandomChooser( const RandomChooser& RC ){}
template< typename T >
inline T Choose( const T& item_1, const T& item_2 )
{
return (rand() % 2) ? item_1 : item_2;
}
};
int main()
{
RandomChooser myChooser;
std::cout << myChooser.Choose( 1.0, 9.9 ) << std::endl;
std::cout << myChooser.Choose( "Foo", "Bar" ) << std::endl;
}
The situation is slightly complicated because you only want one call to srand once, in the whole program, so if you declare another chooser somewhere then you'll reset the random number sequence for all the choosers.
Sorry about the slightly pointless and rambling nature of this reply, I just thought that you might like to know what some further possibilities for you function are :o)