Jump to content
Begedeu

srand() ajutor.

Recommended Posts

Posted

Buna seara . Am facut un program in c++ , un joculet in care trebuie sa ghicesti numarul dat de computer .

As vrea sa stiu cum se face un program pe "dos" in care eu sa dau un numar si computerul sa-l ghiceasca .

Multumesc .

Aici programul , ma rog prima parte cu username si pass am vrut sa fac eu ceva dar imi mai trebuie cunostinte .

#include <cstdlib>
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int main(){
srand(time(0));
int numarul=(rand() % 100) +1;
int incercari=0,guess;
cout <<"\tBine ai venit la ghiceste-mi numarul\n\n";
string username;cout<<"Username: ";cin>>username;
string password;cout<<"Password: ";cin>>password;
if (username == "BGD" && password == "blabla") cout <<"Welcome " <<username<< " to our game\n";
else cout <<"Login failed\n";
do
{
cout<<"Ghiceste numarul ";cin>>guess;++incercari;
if (guess < numarul) cout <<"Mai mult\n";
else cout<<"Mai putin\n";
}while(guess!=numarul);
cout <<"\nBravo ai reusit din " <<incercari<< " incercari";
cin.ignore(cin.rdbuf()->in_avail() +1);
getchar();
return 0;
}

Posted

Nu este o idee prea buna sa lasi computerul sa-l ghiceasca. Practic se transforma intr-o problema de bruteforcing. NU folosi srand() ci /dev/urandom. srand() nu este chiar atat de random precum se doreste. Ai putea citi numarul de la tastatura:


int n;
std::cout << "Introduceti un numar:";
std::cin >> n;

Acum citim octeti din std::random_device:


#include <iostream>
#include <string>
#include <map>
#include <random>

int main()
{
std::random_device rd;
std::map<int, int> hist;
std::uniform_int_distribution<int> dist(0, 9);
for (int n = 0; n < 20000; ++n) {
++hist[dist(rd)]; // note: demo only: the performance of many
// implementations of random_device degrades sharply
// once the entropy pool is exhausted. For practical use
// random_device is generally only used to seed
// a PRNG such as mt19937
}
for (auto p : hist) {
std::cout << p.first << " : " << std::string(p.second/100, '*') << '\n';
}
}

Sursa:

std::random_device - cppreference.com

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...