Hello senorGoat,
To start with "srand" only needs to be done once and should be done in "main". By putting "srand" in the function you could be using the same time value for 2 or more loops.
Next the function returns an "int", but you never collect this in "main". A "void" function works fine.
In the function the call the call to "rand" the (+ 1) is not needed. You can make use of what you have with:
1 2 3
|
num = rand() % 2;
if (num)
|
This works because the if condition evaluates to either false (0) or true (1) and because any number greater then (0) is considered true it works.
I suggest that you watch this:
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful It should give you a better idea how "rand()" works.
This is also worth reading:
https://web.archive.org/web/20180123103235/http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/
In "main" the while loop works, but I would have went with a for loop based on what you have to work with. Either way is fine and do not feel that you have to change the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void coinToss()
{
int num;
rand();
num = rand() % 2;
if (num)
cout << "Heads" << endl;
else
cout << "Tails" << endl;
}
int main()
{
int times, i = 0;
srand(static_cast<size_t>(time(nullptr))); // <--- Noved and changed.
cout << "How many times should the coin be tossed? "; // <--- Removed the "end;". Puts input on the same line.
cin >> times;
cout << '\n';
while (i < times) //It shows the same answer 'x' times :(
{
coinToss();
i++;
}
}
|
Line 11 you may fine useful or not. Sometimes an empty call to "rand()" may give you numbers that seem more random.
This worked and produced a run of:
How many times should the coin be tossed? 10
Heads
Tails
Heads
Tails
Tails
Heads
Heads
Tails
Tails
Tails
|
A run at a different time produced this:
How many times should the coin be tossed? 10
Tails
Tails
Tails
Heads
Tails
Tails
Tails
Heads
Tails
Tails
|
Give it a try and see what you think.
Andy