Zum Inhalt springen
View in the app

A better way to browse. Learn more.

Fachinformatiker.de

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Zufallszahlen zwischen 0 und 1

Empfohlene Antworten

Veröffentlicht

Hi,

ich bekomms einfach nicht gebacken ne Zufallszahl zwischen 0 und 1 zu erstellen :-(

Kann mir jemand helfen?

Hier der Code:

#include <iostream>

#include <time.h>

using namespace std;

int main()

{

int var = 0 ;

srand ( (unsigned)time (0));

for(0<=var<=1;)

{

var =(double)rand()/RAND_MAX;

cout<< var<<endl;

}

cin.get();

cin.get();

return 0;

}

schonma vielen dank

mfg Kevin

#include<iostream>

#include<cmath>

using namespace std;

int main (void)

{

srand ( time(NULL) );

cout << rand()%2 << endl;

cin.get();

}

danke erstmal für die hilfe

muss es nicht ctime anstatt cmath heißen?

und so gibt er mir nur 0 oder 1 aus

ich hätte aber gerne zahlen wie 0.2 oder 0.5

hat jemand ne erklärung im internet oder so?

also wo rand bzw srand anschaulich erklärt ist?

Erzeuge dir einfach Zufallszahlen zwischen 0 und 100; teile anschließend die Zufallszahl durch 100. Damit hast du dann eine Zufallszahl zwischen 0 und 1.

die idee hatte ich auch schon

aber das zählt bei unserer lehrerin nicht...

habs mittlweile zum laufen bekommen:

#include <iostream>

using namespace std;

int main()

{

double zahl = 0, seed;

int a = 0;

cout<<"Startwert eingeben : "<<endl;

cin>>seed;

srand (seed);

while(a <= 20)

{

zahl =(double)rand()/RAND_MAX;

a++;

cout<< zahl <<endl;

}

cin.get();

cin.get();

return 0;

}

aber was hat es damit aufsich: zahl =(double)rand()/RAND_MAX;

was tut dieser befehl??

aber was hat es damit aufsich: zahl =(double)rand()/RAND_MAX;

was tut dieser befehl??

Er konvertiert int/int nach double, damit das Komma nicht abgeschnitten wird.

Er konvertiert int/int nach double, damit das Komma nicht abgeschnitten wird.

Nicht ganz.

rand gibt int zurück, RAND_MAX ist auch ganzzahlig. Daher würde dort normalerweise eine Ganzzahldivision durchgeführt, wobei dann meistens 0 und ganz selten 1 herauskommen würde. Daher wird der Dividend (rand()) dieses Quotientent auf double gecastet, damit der Compiler hier eine Fließkommadivision durchführt.

Archiv

Dieses Thema wurde archiviert und kann nicht mehr beantwortet werden.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.