int main(void)
{
/ Initialize variables and function prototype/
unsigned int seed;
int heads = 0, tails = 0, tosses, k, x;
/* Get user inputs */printf("Enterthenumberoftosses:\n");scanf("%i",&tosses);printf("Enterapositiveintegerseedvalue:\n");scanf("%u",&seed);srand(seed);/* Generate a certain number of tosses. */for(k=1;k<=tosses;k++){x=rand()%2;if(x==1)heads++;elseif(x==0)tails++;}printf("NumberofHeads:%iNumberoftails:%i\n"),heads,tails;system("PAUSE");/* Exit Program */return0;
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
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
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;
}
/-------------------------------------------------------------------------/
WHEN I COMPILE IT I GET WEIRD OUTPUTS!?!
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.
Specifically, this one;
printf("Number of Heads: %i Number of tails: %i \n"), heads, tails;
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