0

I'm trying to generate steps for a drunk man who is 100 steps from home it takes for him to get home. He has a 1/3 probability to take position-= and 2/3 to take position+=. But my code just keeps outputting 100 steps. I'm not sure what I did wrong

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int randomStep(int position);
int main() {

  srand(time(NULL));
  int position = 0, countSteps = 0;
  const int HOME = 100;

  do { // condition is evaluated afterthe execution of the statement
    position = randomStep(position);
    countSteps++;//Counting number of steps to reach home
  } while (position < HOME);

  cout << "No of Steps to reach home : " << countSteps << endl;

  return 0;
}

int randomStep(int position) { //will return the current position of the drunked person
int randomnum = ((rand()) / (RAND_MAX)); // Generating the random number between 0 and 1

if (randomnum < (1/3)) { // if random number is < 1/3, decrease position by 1
  position -= 1;
}
else { // If random number is greater than 1/3 then increase the position by 1
  position += 1;
}
return position;
}
Christian
  • 4,902
  • 4
  • 24
  • 42
  • 1
    ⟼Remember, it's always important, *especially* when learning and asking questions on Stack Overflow, to keep your code as organized as possible. [Consistent indentation](https://en.wikipedia.org/wiki/Indentation_style) helps communicate structure and, importantly, intent, which helps us navigate quickly to the root of the problem without spending a lot of time trying to decode what's going on. – tadman Oct 07 '22 at 01:30
  • 2
    **WARNING**: Using [`rand()` is really awful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) and you’re strongly encouraged to use an appropriate [random number generator facility in the Standard Library](http://en.cppreference.com/w/cpp/numeric/random) that produces high-quality random values. Using `time(NULL)` as a random number will produce identical results if run in the same second, and on many platforms `rand()` is *barely* random at all. – tadman Oct 07 '22 at 01:31
  • 4
    Hint: What do you think `1/3` is for an `int`? What does `rand() / RAND_MAX` end up being for an `int`? – tadman Oct 07 '22 at 01:31
  • @tadman it end up being 0 for int? so should i put .33 instead? – Damien Torres Oct 07 '22 at 01:59
  • Hint: What does `int` mean? How does this differ from things like `float`? – tadman Oct 07 '22 at 04:32
  • `((rand()) / (RAND_MAX))` should be written `rand() / RAND_MAX`. That doesn't fix the problem, but those parentheses didn't do anything except make the code harder to read. – Pete Becker Oct 07 '22 at 13:46

0 Answers0