What is wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

17th Nov 2018, 12:31 PM
Link Skwor
Link Skwor - avatar
2 Answers
+ 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.
17th Nov 2018, 12:53 PM
Shadow
Shadow - avatar
0
Shadow thanks, you are right
17th Nov 2018, 1:22 PM
Link Skwor
Link Skwor - avatar