I'm working on a lab for an introductory C++ course (we've learned strings, chars, cmath, if and if-else, for and while loops, and we just learned functions) and I tested my code (using cloud 9 as our IDE) and it worked fine but when I submitted it to our course submission size (zyBooks) I got some errors that I don't understand.
Our assignment is the follow: Write a program that simulates flipping a coin to make decisions. The input is how many decisions are needed, and the output is either heads or tails. Assume the input is a value greater than 0. For reproducibility needed for auto-grading, seed the program with a value of 2. In a real program, you would seed with the current time, in which case every program runs output would be different, which is what is desired but can't be auto-graded.
Your program must define and call a function: string HeadsOrTails() that returns "heads" or "tails".
NOTE: A common student mistake is to call srand() before each call to rand(). But seeding should only be done once, at the start of the program, after which rand() can be called any number of times.
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
|
#include <iostream>
#include <cstdlib>
using namespace std;
string HeadsOrTails(int iterations) {
int randomValue;
string decision = "";
int i;
srand(2);
for (i = 0; i < iterations; ++i) {
randomValue = rand() % 2;
if (randomValue == 0) {
decision.append("heads\n");
}
else {
decision.append("tails\n");
}
}
return decision;
}
int main () {
int numberOfDecisions;
cin >> numberOfDecisions;
cout << HeadsOrTails(numberOfDecisions);
return 0;
}
|
Should I not have had HeadsOrTails do the loop, but rather have the loop in main and it runs the HeadsOrTails function as many times as was asked by the user?