Dies ist eine Hausaufgabenfrage, aber es ist ein kleiner Teil eines viel größeren Projekts. Eine der Einschränkungen besteht darin, dass wir STL aus keinem Grund verwenden dürfen.Generieren von Zufallszahlen ohne Verwendung von CSTDLIB?
Ich habe versucht, meine eigene rand() -Funktion mit Ctime und einem inkrementierenden Modifikator zu rollen. Ich dachte mir, dass die Funktion, obwohl sie keinen konsistenten Anfangswert hat, Halb-Zufallszahlen ausgeben sollte, solange sie nicht mehr als einmal pro Sekunde denselben Modifikator erhält.
//notcstdlib.cpp
//<ctime> <cmath>
int rand(int mod)
{
time_t seed;
return std::abs(seed * mod);
}
aber dieser Beispielcode
//main.cpp
#include "notcstdlib.h"
#include <iostream>
int main(int argc, char** argv)
{
int f;
for(int i = 1; i <= 10; i++)
{
f = rand(i);
std::cout << "random num= " << f << "\n";
std::cout << "rand % 10 = " << f%10 << "\n";
}
return 0;
}
Immer 7 als der erste Wert zurückgibt und nur gerade Zahlen zwischen 0 und 8 für jede andere Zahl.
//Output 1 //Output 2 //Output 3
random num= 134514987 | random num= 134514987 | random num= 134514987
rand % 10 = 7 | rand % 10 = 7 | rand % 10 = 7
random num= 13261304 | random num= 24238584 | random num= 27941368
rand % 10 = 4 | rand % 10 = 4 | rand % 10 = 8
random num= 19891956 | random num= 36357876 | random num= 41912052
rand % 10 = 6 | rand % 10 = 6 | rand % 10 = 2
random num= 26522608 | random num= 48477168 | random num= 55882736
rand % 10 = 8 | rand % 10 = 8 | rand % 10 = 6
random num= 33153260 | random num= 60596460 | random num= 69853420
rand % 10 = 0 | rand % 10 = 0 | rand % 10 = 0
random num= 39783912 | random num= 72715752 | random num= 83824104
rand % 10 = 2 | rand % 10 = 2 | rand % 10 = 4
random num= 46414564 | random num= 84835044 | random num= 97794788
rand % 10 = 4 | rand % 10 = 4 | rand % 10 = 8
random num= 53045216 | random num= 96954336 | random num= 111765472
rand % 10 = 6 | rand % 10 = 6 | rand % 10 = 2
random num= 59675868 | random num= 109073628 | random num= 125736156
rand % 10 = 8 | rand % 10 = 8 | rand % 10 = 6
random num= 66306520 | random num= 121192920 | random num= 139706840
rand % 10 = 0 | rand % 10 = 0 | rand % 10 = 0
Offensichtlich fehlt mir etwas wichtiger Aspekt der rand() und ich bin der Umsetzung nicht. Gibt es einen besseren Weg, dieses Problem anzugehen?
Ist die Aufgabe, einen eigenen Pseudozufallszahlengenerator zu schreiben? –
Werfen Sie einen Blick hier: https://en.wikipedia.org/wiki/Linear-feedback_shift_register – DimChtz
Siehe https://stackoverflow.com/questions/3062746/special-simple-random-number-generator –