Menu

Heads or Tails. Why wont this work?

2009-03-10
2012-09-26
  • Andrew Charbonneau

    include <stdio.h>

    include <stdlib.h>

    int main(void)
    {
    / Initialize variables and function prototype/
    unsigned int seed;
    int heads = 0, tails = 0, tosses, k, x;

    /* Get user inputs */
    printf(&quot;Enter the number of tosses: \n&quot;);
    scanf(&quot;%i&quot;,&amp;tosses);
    printf(&quot;Enter a positive integer seed value: \n&quot;);
    scanf(&quot;%u&quot;,&amp;seed);
    srand(seed);
    
    /* Generate a certain number of tosses. */
    for (k=1;k&lt;=tosses;k++)
    {
      x = rand()%2;
      if (x == 1)
        heads++;
      else if (x == 0)
        tails++; 
    }
    printf(&quot;Number of Heads: %i  Number of tails: %i \n&quot;), heads, tails;
    
    system (&quot;PAUSE&quot;);
    /* Exit Program */
    return 0;
    

    }
    /-------------------------------------------------------------------------/

    WHEN I COMPILE IT I GET WEIRD OUTPUTS!?!

     
    • Eu Genek

      Eu Genek - 2009-03-11

      It might be useful to define "WHEN I COMPILE IT I GET WEIRD OUTPUTS!?! "

      The printf statement provided in the code looks incorrect to me.

       
    • Eu Genek

      Eu Genek - 2009-03-11

      Specifically, this one;

      printf("Number of Heads: %i Number of tails: %i \n"), heads, tails;

       
      • cpns

        cpns - 2009-03-11

        Agreed. It is valid - i.e. it will compile, but it is semantically meaningless. It means:

        Evaluate: printf("Number of Heads: %i Number of tails: %i \n")
        Then evaluate: heads
        Then evaluate: tails

        These last two have no effect - there's nothing much to evaluate! The printf() however is lacking the two arguments specified by the format string, so will display whatever junk happens to be on the stack.

        Note that using the -Wformat -Werror compiler options will catch such errors. All -Wall too for good measure.

        Clifford

         

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.