Zufallszahl in C++?
Jemand eine einfache Methode zufahlszahlen in c++ unter Linux zu generieren?
Bitte keine Links zu anderen C/C++ - Foren oder sonstigen komplizierten Seiten, ich suche wirklich eine kurze und vrständliche Variante die nicht nur Nerds verstehen.
2 Antworten
Ich habe da neulich mal etwas ausprobiert, ich hoffe, dass es für dich verständlich ist:
// C++
// 26.04.2021
// Zweck: Lottozahlen ermitteln (läuft opitmal)
// Pfad: lotto.cpp
#include <iostream>
#include <algorithm>
#include <time.h>
#include <iomanip>
using namespace std;
int vorhandenF(int, int*); // Deklaration Funktion vorhandenF
int main(void)
{
int lzahlen[6]; // Deklaration Array lzahlen 6 Elemente
int i, xi;
int zufzahl; // Zufallszahl Variable
for (i=0;i<6;i++) // Array lzahlen 6 Elemente auf Null setzen
lzahlen[i] = 0;
// Ziehung
// 6 Durchgänge sofern Zufahlszahl nicht schon vorhanden ist
srand((unsigned)time(NULL)); // Zufallsgenerator initialsieren
for (i=0;i<6;i++) // Ziehungsschleife
{
do
{
zufzahl = 0 + (rand() % 49 + 1); // Zufallszahl ermitteln
}
while (vorhandenF(zufzahl,lzahlen)); // Funktionsaufruf Funkt. vorhandenF
lzahlen[i] = zufzahl;
// nur wenn Wert noch nicht vorhanden wird er in lzahlen Array übernommen
}
// unsortierte Ausgabe
cout << endl << endl << "--------------------------------------------" << endl;
cout << "Lottozahlen nach Ziehung: ";
for (xi=0;xi<6;xi++)
cout << setw(3) << right << lzahlen[xi];
cout << endl << endl;
// sortierte Ausgabe
cout << "Lottozahlen sortiert : ";
// Aufsteigende Sortierung
sort(std::begin(lzahlen), std::end(lzahlen));
for (i=0;i<6;i++)
cout << setw(3) << right << lzahlen[i];
cout << endl;
cout << "--------------------------------------------" << endl;
return 0;
}
// Funktions vorhandenF
// ++++++++++++++++++++++
int vorhandenF(int zufzahl,int lzahlen[6])
{
int i;
for (i=0;i<6;i++)
if (zufzahl == lzahlen[i]) // wenn Wert schon vorhanden ist Abbruch
return 1;
return 0;
}
https://en.cppreference.com/w/cpp/numeric/random/rand
Viel einfacher wird's nicht. Und das funktioniert sogar unter Windows, FreeBSD oder MacOS ;-)
Man beachte aber
rand() is not recommended for serious random-number generation needs. It is recommended to use C++11's random number generation facilities to replace rand(). (since C++11)