Thread: frequency?

  1. #1
    Registered User tu_user's Avatar
    Join Date
    Jan 2004
    Posts
    36

    Question frequency?

    Code:
    #include<iostream>	/* include header files */
    #include<conio.h>	/*                      */
    #include<iomanip>	/*                      */
    
    using std::cout;
    using std::cin;
    using std::endl;
    using std::setw;
    
    void flip();	// prototype
    
    int main()
    {
    	flip();	// function call
    }
    
    void flip(void)
    {
    	int frequency1=0;	// declare & initialize frequency1 to 0
    	int frequency2=0;	// declare & initialize frequency2 to 0
    	int face;	// declare face
    
    	for(int toss=1; toss<=100; toss++)	// coin tossed 100 times
    		face=1+rand()%2;	// generate randomly 1 | 2
    	switch(face)	// switch face
    	{
    	case 1:
    		++frequency1;	// increment heads
    		break;
    	case 2:
    		++frequency2;	// increment tails
    		break;
    	default:
    		cout<< "It should never get here:";	// default should never occur
    		break;	// optional
    	}	// exit switch
    	
    	cout<< setw(10) << "Face" << setw(13) << "Frequency" << endl;	// display results
    	cout<< setw(10) << "Heads" << setw(13) << frequency1 << endl;
    	cout<< setw(10) << "Tails" << setw(13) << frequency2 << endl;
    }
    I am using microsoft visual c++ compiler. It only gives me 0 for heads and 1 for tails. Should it not give random values, I mean some times 0 for tails and some times 1 for heads. The program should toss the coin 100 times and should give each frequency 50 cus equal number of 1's or 0's for tails and heads generate. I dont understand this output. Should I be using srand() and seed thing?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    for(int toss=1; toss<=100; toss++) // coin tossed 100 times
    face=1+rand()%2; // generate randomly 1 | 2

    You need more braces - without them, it's only this much code which is repeated 100 times.
    The switch statement is executed just once.
    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.

  3. #3
    Registered User tu_user's Avatar
    Join Date
    Jan 2004
    Posts
    36

    Thumbs up

    Thanku Salem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Determining CPU frequency
    By pgzh in forum Linux Programming
    Replies: 7
    Last Post: 03-17-2008, 10:34 AM
  2. I need to play a pre recorded vox file using C
    By m.sudhakar in forum C Programming
    Replies: 4
    Last Post: 11-17-2006, 06:59 PM
  3. Frequency density of spectrogra[ph/m]
    By doubleanti in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 12-29-2004, 03:48 AM
  4. Replies: 5
    Last Post: 11-20-2003, 01:27 AM