对《C语言解析教程》中的正反面游戏的修正

来源:互联网 发布:淘宝网上都可以卖什么 编辑:程序博客网 时间:2024/05/16 13:44

《C语言解析教程》(中文版)中正反面游戏的源程序不完整,头文件中声明的:

report_a_win()函数和void report_a_loss()函数都没有定义。另外,在Windows环境下,不能新建prn.c文件(prn.*文件是系统保留文件),将其改为report.c文件,并在其中定义了report_a_win()函数和void report_a_loss()函数。

以下是其完整的源程序:

1.头文件heads_or_tails.h

#include <stdio.h>
#include <stdlib.h>

#define MAXWORD 100

int  get_call_from_user(void);
void play(int how_many);
void prn_final_report(int win, int loss, int how_many);
void prn_instructions(void);
void report_a_win(int coin);
void report_a_loss(int coin);
int  toss(void);  

2.get.c 文件

#include "heads_or_tails.h"

int get_call_from_user(void)
{
 int guess;
 do{
    printf("call it:  ");
    if(scanf("%d",&guess)!=1){
     printf("/nSORRY:Severe input error - bye!/n/n");
     exit(1);
    }
    if(guess!=0 && guess!=1){
     printf("/n%s/n/n",
       "ERROR:Type 0 for heads, 1 for tails.");
    }
 }while(guess!=0 && guess!=1);
 return guess;
}

3.play.c文件

#include "heads_or_tails.h"
#include "time.h"
#include "stdlib.h"

int toss(void)
{
 srand(time(0));
 return (rand()%2);
}

void play(int how_many)
{
 int coin, i, loss=0, win=0;
 for(i = 0;i<how_many; ++i){
    coin = toss();
    if(get_call_from_user() == coin){
     ++win;
     report_a_win(coin);
    }
    else{
     ++loss;
     report_a_loss(coin);
    }
   }
   prn_final_report(win, loss, how_many);
}

4.report.c文件

#include "heads_or_tails.h"

void prn_instructions(void)
{
 printf("%s/n",
   "This is the game of calling heads or tails./n"
   "I will flip a coin;you call it. If you/n"
   "call it correctly,you win;otherwise,/n"
   "I win./n"
   "/n"
   "As I toss the(simulated)coin,I will/n"
   "tell you to /"call it./"  To call heads,/n"
   "type 0;to call tails,type 1./n"
   "/n");
}

void report_a_win(int coin){
 printf("the coin is %d,you guess it :)/n ", coin);
}

void report_a_loss(int coin){
    printf("the coin is %d,you didn't guess it :(/n ", coin);
}

void prn_final_report(int win,int loss,int how_many)
{
 printf("/n%s/n%s%3d/n%s%3d/n%s%3d/n/n",
   "FINAL REPORT:",
   "  Number of games that you won:  ", win,
   "  Number of games that you loss: ", loss,
   "  Total number of games:         ", how_many);
}

5.main.c主函数文件

#include "heads_or_tails.h"

int main()
{
 char ans;
 int no_of_plays;

 printf("/n"
   "---THE GAME OF HEADS OR TAILS---/n"
   "/n"
   "---Do you want instruceions?  ");
 scanf("%c",&ans);
 putchar('/n');
 if(ans == 'y' || ans == 'Y')
  prn_instructions();
 printf("How many times do you want to play? ");
 scanf("%d",&no_of_plays);
 putchar('/n');
 play(no_of_plays);
 return 0;
 }

通过gcc 3.4.2编译

原创粉丝点击