There is a program that simulates a coin toss. The problem is that, logically, it should throw out about 50 to 50 (Eagle-Reshka), but why is the ratio around 30 to 70, why can you explain this? (Devc ++, win7)

#include <stdio.h> #include <stdlib.h> #include <time.h> int flip(void); main() { srand(time(NULL)); int sumReshka = 0, sumOrel = 0; for (int i = 1; i <= 100; i++) { if (flip() == 0) { sumReshka++; printf("Reshka\n"); } else { sumOrel++; printf("Orel\n"); } } printf("Kol-vo reshek - %d, Kol-vo orlov - %d\n", sumReshka, sumOrel); system("PAUSE"); } int flip(void) { if ((rand() % 2) == 1) return 1; else if ((rand() % 2) == 0) return 0; } 
  • I wonder how you could compile it at all? You do not have return 'but in the flip function. - VladD
  • one
    @VladD warning C4715: flip: not all return paths are returned. - manking
  • 2
    @manking: I wonder what returns from the function in this case? random rubbish? - VladD
  • one
    No, wrong said. All the same garbage. If inside the function to create and initialize for example std :: string, then the address of this first variable will be returned. If after the last return in the function to initialize the array, then the address of the first element of this array will be returned. If this is done before, it will return 0. - manking
  • five
    @manking, EMNIP on a PC in the general case will be the value of ax / eax / ax: dx / eax: edx (depending on the type of return). And what gets into them is a matter of chance and a compiler optimizer :)) - user6550

1 answer 1

instead

 int flip(void) { if ((rand() % 2) == 1) return 1; else if ((rand() % 2) == 0) return 0; } 

you need to write

 int flip(void) { return (rand() % 2); } 

In the first variant, you call rand () twice. That is, an eagle falls in 50% of cases, and if it does not fall out, then you call rand () again and return what you end up with, that is, another result rand ()% 2. Therefore, the average eagle happens to you 75% of cases

  • I'm understood, thank you. - Stee1House