Strange. I am getting an "Uninitialized local variable" on the cointoss(void) section of my code for the "return randomnumber;" line I'll post the code I have so far. I just can't tell what is wrong with it. What am I missing?
Could it be because of Microsoft visual studio? That's the program I use for coding. I am clearly getting a syntax error for line 11. What program are you using SamuelAdams?
In int cointoss(void), the variable randomnumber is not initialised. It is also never assigned to. The function, finally returns the uninitialised value.
1 2 3 4 5 6 7 8 9
int cointoss(void)
{
int randomnumber; // *** not initialised
randomnumber - 1 + rand() % 2; // *** computes a value and then discards the result
return randomnumber; // *** return the uninitialised value
}
This is probably what you intended to do:
1 2 3 4 5 6 7 8 9
int cointoss(void)
{
int randomnumber;
randomnumber = 1 + rand() % 2; // *** note: = (assignment)
return randomnumber; // fine: return the value after it was assigned to
}
#include <iostream>
#include <cstdlib>
#include <ctime>
// note that this is not a great idea: it relies on the randomness
// of the low-order bit of the pseudo random number generated by
// a random number generator of suspect quality.
// for better options, see: http://en.cppreference.com/w/cpp/numeric/randombool got_a_head() { return std::rand()%2 ; }
void toss_a_coin()
{
if( got_a_head() ) std::cout << "head\n";
else std::cout << "tail\n";
}
int main()
{
int howmanytimes = 0;
std::cout << "How many times would you like to toss the coin? ";
std::cin >> howmanytimes;
std::srand( std::time(nullptr) ) ;
for( int i = 0; i < howmanytimes; ++i ) toss_a_coin() ;
}
Now that I have scrubbed that "-" from line 11 (Thank you, JLBorges!) I can see what you are talking about, SamuelAdams. I am also getting nothing but "headtail" outputs. (Thank you very much JLBorges!) I bow to my betters. Thank you for the help! You guys both helped me learn a lot from this!