Zufallszahl



  • Hey, habe erst vor zwei Wochen den Einstieg ins Programmieren gefunden und stelle nun eine etwas naive Frage.
    Wie erstelle ich eine Zufallszahl, die der Computer ausgiebt?
    MFG patte



  • kleines Codebeispiel OK?

    #include <cstdlib> /* Für srand und rand */
    #include <iostream> 
    using namespace std;
    
    int main () {
       srand(time(0)); //einmal am Anfang des Programms aufrufen
    
       cout << "(Pseudo)Zufall: " << rand() << "\nNochmal: " << rand() << "\nUnd: " << rand() << '\n';
    }
    


  • Kurzer Blick in die FAQ oder die Suchfunktion hätten dich auch ans Ziel gebracht: http://www.c-plusplus.net/forum/viewtopic.php?t=39344



  • ich mach es immer so:

    //kleines Beispielprogram
    #include<iostream.h>
    #include<stdlib.h>
    int main(void)
    {
      int a,b;
      a=rand() % 99+1; //will keine Null als Zufallszahl
      b=rand() % 99+1;
      cout<<a<<"+"<<b<<"="<<atb<<endl;
      return 0;
    }
    

    vielleicht nicht optimal aber sehr einfach



  • du solltest lieber die standard c++ header nehmen, welche da lauten

    #include <iostream>
    #include <cstdlib>
    

    stdlib.h geht zwar auch noch, aber ist deprecated.
    alle funktionen, typen und objekte sind im namensraum std oder einem namensraum im namensraum std. also mit using öffnen:

    using namespace std;
    
    //oder - wenn du nur einzelne dinge brauchst:
    
    using std::einzelnes_ding;
    

    dazu gibt's noch viel mehr threads, benutz mal die suchfunktion. das thema kommt oft in verbindung mit void main.


Anmelden zum Antworten