0
What is wrong?
I want to cout 5 numbers 1 and 5 numbers 0 but in some occasion it cout a number 2. So why does it cout a number 2? #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int x=0, p=0,s=2, c1=0,c2=0; srand(time(0)); for(int n=0; n<=9; n++ ) {x= p+rand() % s; cout<<x<<endl; if(x==0){c1++;} if(x==1){c2++;} if(c1==5){p=1;} if(c2==5){s=1;} } return 0; } https://code.sololearn.com/c1xrM38iLi08/?ref=app
2 ответов
+ 2
It sometimes outputs a 2 because if the first counter 'c1' is triggered, you set 'p' to 1 without decreasing 's'. Because 's' is still 2,
rand() % 2
can either evaluate to 0 or to 1, meaning the possible results become
1 + 0 or 1 + 1.
This is where you get your 2 from. You should decrease 's' to 1 when setting 'p' to 1 in the if-case in order to avoid it.
0
Shadow thanks, you are right