Thread: Help with C Monte Carlo

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    Code:
    #include <stdio.h> //std input and output 
    #include <math.h> //math library 
    #include <stdlib.h> //standard libarary 
    
    int main (void)
    {
      printf("Welcome To The Roulette Wheel Simulator. \n \n");
      long cash = 0; //count the number of $1 you win. 
      int p = 0;  //probability is an integer here to allow for rand. 
      double probability = 0; //hasn't been used yet. 
      int games = 0;  
      //pseudo-random number generator
      int counter;
      for(counter = 0; counter < 1000; counter++)
      {
        int p = 0;
        p = rand()%4737;
        
        if(p >= 526  && counter < 1000) //continue to loop until a loss 
        {    
          cash = cash + 1; //add to cash.
        }
        if(p <= 526)
        { 
          printf(" You lost at %d games\n \n You won $%d \n \n", &counter, &cash);
          printf ("Press Any Key to Exit\n"); 
          break;
        } 
      }
      getch(); 
    }
    1. Learn indentation - SourceForge.net: Indentation - cpwiki

    2. && counter < 1000 will never happen, given the for loop has the same test.

    3. >= 526 and <= 526 overlap at 526. It would have been better to use an else

    4. &counter, &cash - you have to pay attention to what you pass to printf/scanf.
    printf(" You lost at %d games\n \n You won $%ld \n \n", counter, cash);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by Salem View Post
    [code]
    2. && counter < 1000 will never happen, given the for loop has the same test.
    [/FONT]
    Surely you must mean it WILL ALWAYS HAPPEN, BECAUSE it is inside the loop, therefore the loop condition is still true. It is useless, but in no case false.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Monte Carlo reliability program - SegFault :(
    By Kibble Fat in forum C Programming
    Replies: 7
    Last Post: 12-15-2009, 02:41 PM
  2. A new random number generator!
    By Sebastiani in forum General Discussions
    Replies: 19
    Last Post: 07-30-2009, 03:27 PM
  3. finding area of unit circle by monte carlo..
    By niceguy in forum C Programming
    Replies: 4
    Last Post: 02-25-2008, 01:32 PM
  4. Problem with Monte Carlo(integration by rejection)
    By dionys in forum C Programming
    Replies: 9
    Last Post: 04-07-2004, 09:53 AM
  5. monte carlo methods
    By qwertiop in forum C++ Programming
    Replies: 3
    Last Post: 09-05-2001, 11:29 PM