Program from a book not working?

Monado_III

Well-Known Member
OP
Member
Joined
Feb 8, 2015
Messages
722
Trophies
0
Location
/dev/null
XP
1,433
Country
Canada
Don't be dirty!
Flush the output!

Code:
/* Program 4.12 Simple Simon */
#include <stdio.h>                     /* For input and output   */
#include <ctype.h>                     /* For toupper() function */
#include <stdbool.h>                   /* For bool, true, false  */
#include <stdlib.h>                    /* For rand() and srand() */
#include <time.h>                      /* For time() and clock() */

int main(void)
{
  /* Records if another game is to be played */
  char another_game = 'Y';

  /* true if correct sequence entered, false otherwise */
  int correct = false;

  /* Number of sequences entered successfully          */
  int counter = 0;

  int sequence_length = 0;     /* Number of digits in a sequence        */
  time_t seed = 0;             /* Seed value for random number sequence */
  int number = 0;              /* Stores an input digit                 */

  time_t now = 0;            /* Stores current time - seed for random values  */
  int time_taken = 0;        /* Time taken for game in seconds                */

  /* Describe how the game is played */
  printf("\nTo play Simple Simon, ");
  printf("watch the screen for a sequence of digits.");
  printf("\nWatch carefully, as the digits are only displayed"
                                                " for a second! ");
  printf("\nThe computer will remove them, and then prompt you ");
  printf("to enter the same sequence.");
  printf("\nWhen you do, you must put spaces between the digits. \n");
  printf("\nGood Luck!\nPress Enter to play\n");
  scanf("%c", &another_game);

  /* One outer loop iteration is one game */
  do
  {
    correct = true;         /* By default indicates correct sequence entered */
    counter = 0;            /* Initialize count of number of successful tries*/
    sequence_length = 2;    /* Initial length of a digit sequence            */
    time_taken = clock();  /* Record current time at start of game       */

    /* Inner loop continues as long as sequences are entered correctly */
    while(correct)
    {
      /* On every third successful try, increase the sequence length */
      sequence_length += counter++%3 == 0;

      /* Set seed to be the number of seconds since Jan 1,1970  */
      seed = time(NULL);

      now = clock();                  /* record start time for sequence  */

      /* Generate a sequence of numbers and display the number */
      srand((unsigned int)seed);      /* Initialize the random sequence */
      for(int i = 1; i <= sequence_length; i++)
        printf("%d ", rand() % 10);    /* Output a random digit          */

     // (!) Flush the text OUTPUT!!!
     // Otherwise the buffered output waits for a new line (\n) to print data
     fflush(stdout);

      /* Wait one second */
      for(;clock() - now < CLOCKS_PER_SEC*3;);

      /* Now overwrite the digit sequence */
      printf("\r");                   /* go to beginning of the line */
      for(int i = 1; i <= sequence_length; i++)
      printf("  ");                 /* Output two spaces */

     // (!) Flush the text OUTPUT!!!
     // Otherwise the buffered output waits for a new line (\n) to print data
     fflush(stdout);

      if(counter == 1)           /* Only output message for the first try */
        printf("\nNow you enter the sequence  - don't forget"
                                               " the spaces\n");
      else
        printf("\r");                /* Back to the beginning of the line */

      /* Check the input sequence of digits against the original */
      srand((unsigned int)seed);     /* Restart the random sequence    */
      for(int i = 1; i <= sequence_length; i++)
      {
        scanf("%d", &number);         /* Read an input number         */
        if(number != rand() % 10)     /* Compare against random digit */
        {
          correct = false;            /* Incorrect entry             */
          break;                      /* No need to check further... */
        }
      }
      printf("%s\n", correct? "Correct!" : "Wrong!");
    }

    /* Calculate total time to play the game in seconds)*/
    time_taken = (clock() - time_taken) / CLOCKS_PER_SEC;

    /* Output the game score */
    printf("\n\n Your score is %d", --counter * 100 / time_taken);

    fflush(stdin);

    /* Check if new game required*/
    printf("\nDo you want to play again (y/n)? ");
    scanf("%c", &another_game);

  }while(toupper(another_game) == 'Y');
  return 0;
}
That works, thx! I knew about fflush, but didn't know that would help solve this bug.
 

cdoty

Well-Known Member
Member
Joined
Sep 14, 2009
Messages
329
Trophies
0
Website
www.rastersoft.net
XP
352
Country
United States
Tried it and it still didn't work, this is what the program should look like right?

Yep. My guess is the clock stuff doesn't work correctly.

Here's code from the standard C library that will do the same thing:

Code:
#include<stdlib.h>

Replace:

Code:
for(;clock() - now < CLOCKS_PER_SEC*3;);

with:
Code:
sleep(1);

on Linux, etc. you may have to use:
#include<unistd.h> instead of #include<stdlib.h>

--------------------- MERGED ---------------------------

Honestly, you should move on with your book.
A single demo program not working is insignificant compared with the rest of your learning.

This may sound logical, but time spent figuring out a program is valuable also, even if you're asking for help. This is exactly what you will be doing 20-30% of the time at least.

And a broken example is the worse case situation. Not only are you trying to learn, you have to decide if it's broken because of something you did.

It's like learning a new language, staring at a word list doesn't make you better at conversation, conversing does.
 
Last edited by cdoty,
  • Like
Reactions: Monado_III

Monado_III

Well-Known Member
OP
Member
Joined
Feb 8, 2015
Messages
722
Trophies
0
Location
/dev/null
XP
1,433
Country
Canada
Yep. My guess is the clock stuff doesn't work correctly.

Here's code from the standard C library that will do the same thing:

Code:
#include<stdlib.h>

Replace:

Code:
for(;clock() - now < CLOCKS_PER_SEC*3;);

with:
Code:
sleep(1);

on Linux, etc. you may have to use:
#include<unistd.h> instead of #include<stdlib.h>

--------------------- MERGED ---------------------------



This may sound logical, but time spent figuring out a program is valuable also, even if you're asking for help. This is exactly what you will be doing 20-30% of the time at least.

And a broken example is the worse case situation. Not only are you trying to learn, you have to decide if it's broken because of something you did.

It's like learning a new language, staring at a word list doesn't make you better at conversation, conversing does.
That looks like a better solution for this. Thanks.
 

Monado_III

Well-Known Member
OP
Member
Joined
Feb 8, 2015
Messages
722
Trophies
0
Location
/dev/null
XP
1,433
Country
Canada
Yep. My guess is the clock stuff doesn't work correctly.

Here's code from the standard C library that will do the same thing:

Code:
#include<stdlib.h>

Replace:

Code:
for(;clock() - now < CLOCKS_PER_SEC*3;);

with:
Code:
sleep(1);

on Linux, etc. you may have to use:
#include<unistd.h> instead of #include<stdlib.h>



This may sound logical, but time spent figuring out a program is valuable also, even if you're asking for help. This is exactly what you will be doing 20-30% of the time at least.

And a broken example is the worse case situation. Not only are you trying to learn, you have to decide if it's broken because of something you did.

It's like learning a new language, staring at a word list doesn't make you better at conversation, conversing does.
now whenever I get an answer wrong it say there was a floating point exception and that a core was dumped, so I looked here and am assuming the division by zero is happening at here as that is when it crashes. So how would I go about giving CLOCKS_PER_SEC the appropriate value.
Code:
/* Calculate total time to play the game in seconds)*/
    time_taken = (clock() - time_taken) / CLOCKS_PER_SEC;

    /* Output the game score */
    printf("\n\n Your score is %d", --counter * 100 / time_taken);

I really appreciate the help
 

cdoty

Well-Known Member
Member
Joined
Sep 14, 2009
Messages
329
Trophies
0
Website
www.rastersoft.net
XP
352
Country
United States
It shouldn't be zero, it will take at least one second to display the original sequence.

To verify this, add before the 'if' statement:
Code:
printf("Time taken %d\n", time_taken);

You could add this after the 'time_taken =' line:
Code:
if (time_taken <= 0)
{
time_taken = 1;
}

After looking at the code, the only way I can see it happening is if the timer is slightly off and you quickly enter an incorrect digit for the 1st number. The 'if' will fix that.
 
Last edited by cdoty,
General chit-chat
Help Users
  • No one is chatting at the moment.
  • JuanMena @ JuanMena:
    Will you give me mouth to mouth oxygen if my throat closes?
  • K3N1 @ K3N1:
    Nah the air can do that
  • K3N1 @ K3N1:
    Ask @x65943 he's trained for that stuff
  • JuanMena @ JuanMena:
    Kissing random dudes choking in celery? Really? Need to study for that?
  • K3N1 @ K3N1:
    Yes it requires a degree
  • K3N1 @ K3N1:
    I could also yank out the rest of my teeth but theirs professionals for that
  • x65943 @ x65943:
    If your throat closes, putting oxygen in your mouth will not solve anything - as you will be introducing oxygen prior to the area of obstruction
  • JuanMena @ JuanMena:
    Just kiss me Kyle.
  • x65943 @ x65943:
    You either need to be intubated to bypass obstruction or create a stoma inferior to the the area of obstruction to survive
  • x65943 @ x65943:
    "Just kiss me Kyle." And I thought all the godreborn gay stuff was a smear campaign
  • JuanMena @ JuanMena:
    If I die, tell my momma I won't be carrying Baby Jesus this christmas :sad::cry:
  • K3N1 @ K3N1:
    Smear campaigns are in The political section now?
  • JuanMena @ JuanMena:
    Chary! Chary! Chary, Chary, Chary!
  • Sonic Angel Knight @ Sonic Angel Knight:
    Pork Provolone :P
  • Psionic Roshambo @ Psionic Roshambo:
    Sounds yummy
  • K3N1 @ K3N1:
    Sweet found my Wii u PSU right after I ordered a new one :tpi:
  • JuanMena @ JuanMena:
    It was waiting for you to order another one.
    Seems like, your PSU was waiting for a partner.
  • JuanMena @ JuanMena:
    Keep them both
    separated or you'll have more PSUs each year.
  • K3N1 @ K3N1:
    Well one you insert one PSU into the other one you get power
  • JuanMena @ JuanMena:
    It literally turns it on.
  • K3N1 @ K3N1:
    Yeah power supplies are filthy perverts
  • K3N1 @ K3N1:
    @Psionic Roshambo has a new friend
    +1
  • JuanMena @ JuanMena:
    It's Kyle, the guy that went to school to be a Certified man Kisser.
  • Psionic Roshambo @ Psionic Roshambo:
    Cartmans hand has taco flavored kisses
  • A @ abraarukuk:
    hi guys
    A @ abraarukuk: hi guys