0

Whats wrong with my code?

You must set a PIN for your suitcase that contains 4 digits in the range of 0 to N. Write a program to take the N number as input, generate 4 random numbers from the range and print them sequentially, without spaces. Sample Input 9 Sample Output 2818 Code: #include <iostream> #include <cstdlib> using namespace std; int main() { srand(0); int range; cin >> range; //your code goes here rand(); range=range+1; for(int i =0; i<4;i++) { cout<<(rand()% (range)); } return 0; }

5th Dec 2020, 8:03 AM
Psyco Techie
7 Antworten
+ 1
It appears the actual range of numbers to generate is (0, N], i.e. the 0 is exclusive (in case this notation is unfamiliar, parentheses mean the boundary element is not in the range, while a square bracket means it is in the range). Therefore, the problem is that you add 1 to the range beforehand, which means you can generate numbers in the range [0, N]. However, if you add 1 after generating the number, the interval equals 1 + [0, N) = 1 + [0, N - 1] = [1, N] = (0, N]. So basically, try adding 1 to the generated number instead of adding 1 to the range.
5th Dec 2020, 8:10 AM
Shadow
Shadow - avatar
+ 1
As I said, do not add one to the range in this line: range = range + 1; Instead, you should add one to the number you generate in this line: cout << rand() % range; It's a very simple change you should be able to make yourself. However, if you did not understand something about my initial answer, then it might be best to say that so I can try to clarify.
5th Dec 2020, 8:51 AM
Shadow
Shadow - avatar
+ 1
#include <iostream> #include <cstdlib> using namespace std; int main() { srand(0); int range; cin >> range; //your code goes here rand(); for(int i =1; i<=4;i++) { cout<<(rand() % (range)) +1; } return 0; } Shadow still not matching the answer
5th Dec 2020, 9:08 AM
Psyco Techie
+ 1
Try to use sololearn playground for Showing your code
7th Dec 2020, 7:57 AM
Sayyam Jain
Sayyam Jain - avatar
0
Shadow Can you correct it ?
5th Dec 2020, 8:18 AM
Psyco Techie
0
Why are you now generating a fifth number before the loop?
5th Dec 2020, 9:32 AM
Shadow
Shadow - avatar
0
The solution is here, thus; int main() { int range; cin >> range; for (int x = 1; x <= 4 ; x++) { cout << 1 + rand() % range; } }
11th Sep 2021, 2:27 AM
Adinnuh, Kenechukwu
Adinnuh, Kenechukwu - avatar