+ 1
Setting your PIN -exercise
This is my code, in input 4 I should get “4324”. And I have 3120. Run out of ideas. Maybe someone can help ? #include <iostream> #include <cstdlib> using namespace std; int main() { srand(0); int range; cin >> range; range+=1; for (int i=0;i<4;i++) cout <<rand()%range; return 0; }
9 Réponses
+ 6
It appears the actual range 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). That's at least what I figured from the test cases and how I solved the challenge.
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.
+ 2
#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;
}
Good Luck
0
yes yes, result shude be predictable.
and shud be 4324.
i dont want to have unpredicable.
so is 2 option i may did somthing wrong or answer in the solarapp is wrong.
0
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
4
Sample Output
4324
//Use rand() function to generate the numbers from required range.
srand(0) is used to match the output, so don't change it.//
0
Shadw YOU are BEST! Thanks !
0
int main(){
srand(0);
int range;
cin >> range;
for (int i = 0; i < 4; i++){
cout<<rand()%range+1;
}
return 0;
}
0
Add this for loop to your code
for (int i = 0; i < 4; i++){
cout<<rand()%range+1;
}
0
I read the problem and tried to solve it from scratch in VSC so I coded this one, I ran it and everything was OK, My confusion came when I pasted my code in the exercise page and it showed an error, my error was not adding +1 in the for loop 8th line but I don't understand, why do I need to add that +1?, could anyone explain that please?
#include <iostream>
#include <cstdlib>
void PIN(int n){
int pin;
srand(0);
for(int i = 0; i < 4; i++){
pin = 1+ rand() % n;
std::cout<<pin;
}
}
int main(){
int n;
std::cin>>n;
PIN(n);
return 0;
}
0
Working C++ code;
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
srand(0);
int range;
cin >> range;
//your code goes here
int PIN[4];
for(int i=0; i<4; i++)
PIN[i]=1+(rand()%range);
cout<<PIN[0]<<PIN[1]<<PIN[2]<<PIN[3]<<endl;
return 0;
}