+ 1

C++ 40.2 Practice Help

Can any one help me understand why I get a different output from the required test output? This is my code: #include <iostream> #include <cstdlib> using namespace std; int main() { srand(0); int range; cin >> range; //your code goes here for (int i = 0; i < 4; i++) { cout << 0 + (rand() % range); } return 0; } My code outputs a 4 digit number in the range from 0 to N as required, but because it does't match the expected output it fails the practice problem. Any ideas where I am going wrong? Thanks, Mike.

18th Jun 2021, 1:55 PM
Mike
Mike - avatar
3 odpowiedzi
+ 1
You are using rand() which generate random numbers... Can you add problem description for you are trying this..? edit: Mike there rand() produce 0 to n-1 numbers so you need add 1 to get within asking range. #include <iostream> #include <cstdlib> using namespace std; int main() { srand(0); int range; cin >> range; //your code goes here for(int i=0;i<4;i++) cout<<(rand()%range)+1; return 0; }
18th Jun 2021, 7:22 PM
Jayakrishna 🇮🇳
+ 1
Thank you jayakrishna, I managed to figure it out eventually 👍🏻
18th Jun 2021, 7:44 PM
Mike
Mike - avatar
+ 1
👍👌 You're welcome..
18th Jun 2021, 7:48 PM
Jayakrishna 🇮🇳