c program

2007-12-15 9:14 pm
write a program to simulate the game of tossing a coin. ask the user head or tail by pressing the key "H" or"T" respectively. Show the result of the game with an appropriate message.repeat the game until the user presses a key other than "H" and "T".
sample output:
Enter your guess:H
You win!
The outcome is H

Enter your guess:T
You loss!
The outcome is H.

Enter the guess:E
Thank you for trying!

回答 (1)

2007-12-16 4:23 pm
✔ 最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[])
{
srand(time(NULL));
int outcome; // outcome=1 head; outcome=0 tail;
char *outcomeText[2]={"Tail","Head"};
char *message[3]={"You win!","You lose!","Thank you for playing! Press enter to continue..."};
int nMessage;
char answer, lf;
do
{
outcome=rand()%2;
printf("Enter your guess:");
answer=getchar(); // get character entered (line buffered)
lf=getchar(); // dispose of the line-feed character
if(answer=='h'||answer=='H')
{
if(outcome==1)nMessage=0; else nMessage=1;
}
else if(answer=='t'||answer=='T')
{
if(outcome==0)nMessage=0; else nMessage=1;
}
else break;
printf("%s Outcome is %s\n",message[nMessage],outcomeText[outcome]);
}while(1==1);
printf("%s\n",message[2]);
answer=getchar();
return 0;
}


收錄日期: 2021-04-13 14:43:46
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20071215000051KK01531

檢視 Wayback Machine 備份