+ 1
Suitcase pin problem.
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 Can someone tell me what I am doing wrong or at least what exactly I missing? 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<<rand()%range; } return 0; }
4 Respostas
+ 2
Zotta
add 1 in rand() % range
for (int i = 0; i < 4; i++) {
cout << 1 + rand() % range;
}
+ 2
Without the +1 the range of numbers you get is 0..(N-1) because %N can not be greater than N-1. To also get 0 you should have to write rand()%(range+1)
+ 1
Hape oh, so I am losing the N element, that makes sense, thanks
0
🅰🅹 🅐🅝🅐🅝🅣
It work adding 1 at cout, but why it didn't work without it? Mean the pin may contain and number 0 also, and adding exclude that option.