I'm stuck with a problem. I'm making the Rock-Paper-Scissors game for my homework, but I don't know how to generate the number using just 3 specific given number and convert to character using char and ASCII Those given numbers are : 66, 71 and 75
答案 0 :(得分:1)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char getRandomChar()
{
srand(time(NULL));
auto randomnumber = rand() % 3;
char buf[3]={66, 71 , 75};
return buf[randomnumber];
}
答案 1 :(得分:1)
这是我的解决方案。
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
/* initialize random seed: */
srand (time(NULL));
enum Choice {ROCK,PAPER,SCISSORS};
do {
printf("Please enter your choice: ");
char yours; //your choice
scanf(" %c",&yours);
if (yours=='q'){
break;
}
Choice computers = static_cast<Choice>( rand() % 3 );
if ((yours=='r' && computers==ROCK)||
(yours=='p' && computers==PAPER)||
(yours=='s' && computers==SCISSORS))
{
printf("Its a draw.\n\n");
continue;
}
if ((yours=='r' && computers==SCISSORS)||
(yours=='p' && computers==ROCK)||
(yours=='s' && computers==PAPER))
{
printf("Congratulations, you won!\n\n");
} else {
printf("Sorry, you loose :-( \n\n");
}
} while(true);
return 0;
}
使用ASCII表中的字符r
,p
,s
接近这一事实存在一个hacky解决方案。 ASCII中p
的位置为112.您可以计算rand()%4 + 112并将其与转换为int的char进行比较。
答案 2 :(得分:0)
此代码将从您的三个数字中选择一个,在这种情况下,它会将它们输出到输出流...
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); // ensure truly randomized number
int nums[3] = {66, 71, 75};
int i = rand() % 3; // find random number between 0 and 2
cout << nums[i] << endl;
return 0;
}
答案 3 :(得分:0)
以下是使用ASCII编号的解决方案。它将为您节省一些代码。
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
/* initialize random seed: */
srand (time(NULL));
enum Choice {PAPER=112, QUIT, ROCK, SCISSORS};
do {
printf("Please enter your choice (r/p/s; q to quit): ");
char yours; //your choice
scanf(" %c",&yours);
if (yours=='q'){
break;
}
Choice computers;
do {
computers = static_cast<Choice>( 112 + rand() % 4 );
} while (computers==QUIT);
if (yours==computers)
{
printf("Its a draw.\n\n");
continue;
}
if ((yours=='r' && computers==SCISSORS)||
(yours=='p' && computers==ROCK)||
(yours=='s' && computers==PAPER))
{
printf("Congratulations, you won!\n\n");
} else {
printf("Sorry, you loose :-( \n\n");
}
} while(true);
return 0;
}