rand() obere und untere Grenze zuweisen



  • Ich möchte mit rand(); Zufallszahlen erzeugen.
    Wie kann ich eine obere und untere Grenze festlegen.
    Ich benötige nur ganze positive Zahlen z.B.
    zwischen 0 und 255.

    Weiss jemand wie das geht?



  • long lVal = rand() % 255; // 0-255
    long lVal = rand() % 255 + 100; // 100-355
    long lVal = rand() % 255 - 100; // -100-155
    


  • ok, aber die unteren beiden Zeilen check ich nicht.
    Hmm, kannst nochmal bissle Info rüberschicken, oder
    einen Link wo Rand() im Details beschrieben ist.



  • Sovok schrieb:

    long lVal = rand() % 255; // 0-255
    

    0-254



  • @volkard jo stimmt

    Steev schrieb:

    ok, aber die unteren beiden Zeilen check ich nicht.
    Hmm, kannst nochmal bissle Info rüberschicken, oder
    einen Link wo Rand() im Details beschrieben ist.

    also wir holn uns ne zahl zwischen 0 und 254

    long lVal = rand() % 255; // 0-254
    

    jetzt addiern wir 100 und ham ne zahl zwischen 100 und 354

    lVal += 100;
    

    oder ziehn 100 ab und ham ne zahl zwischen -100 und 154

    lVal -= 100;
    

    das ganze halt als ein schritt

    long lVal = rand() % 255 + 100; // 100-354
    long lVal = rand() % 255 - 100; // -100-154
    

    gaaanz simpel 🙂



  • oder so, dann muss man das nicht jedes mal machen:

    long myrand(long const& min, long const& max)
    {
        return (rand() % (max - min + 1)) + min;
    }
    

Anmelden zum Antworten