【发布时间】:2016-10-26 00:37:40
【问题描述】:
这是我遇到问题的代码。
#include <stdio.h>
int getplayerone (void);
int getplayertwo (void);
void output (int getplayerone (), int getplayertwo ());
enum choice
{ r, p, s };
typedef enum choice Choice;
int
main (int argc, char *argv[])
{
//getplayerone();
// getplayertwo();
output (getplayerone (), getplayertwo ());
return 0;
}
int
getplayerone (void)
{
char choice1;
int choice1int;
printf ("Player-1 it is your turn!\n");
printf ("Please enter your choice (p)aper, (r)ock, ir (s)cissors: ");
scanf (" %c", &choice1);
if (choice1 == 'r' || choice1 == 'R')
{
choice1int = 0;
}
else if (choice1 == 'p' || choice1 == 'P')
{
choice1int = 1;
}
else if (choice1 == 's' || choice1 == 'S')
{
choice1int = 2;
}
if (choice1int == 0)
{
}
return choice1int;
}
int
getplayertwo (void)
{
char choice2;
int choice2int;
printf ("\nPlayer-2 it is your turn!\n");
printf ("Please enter your choice (p)aper, (r)ock, ir (s)cissors: ");
scanf (" %c", &choice2);
if (choice2 == 'r' || choice2 == 'R')
{
choice2int = 0;
}
else if (choice2 == 'p' || choice2 == 'P')
{
choice2int = 1;
}
else if (choice2 == 's' || choice2 == 'S')
{
choice2int = 2;
}
return choice2int;
}
void
output (int getplayerone (), int getplayertwo ())
{
Choice p1choice = getplayerone ();
Choice p2choice = getplayertwo ();
if (p1choice == r && p2choice == r)
{
printf ("Draw");
}
else if (p1choice == r && p2choice == p)
{
printf ("Player 2 wins");
}
else if (p1choice == r && p2choice == s)
{
printf ("Player 1 wins");
}
else if (p1choice == s && p2choice == r)
{
printf ("Player 2 wins");
}
else if (p1choice == s && p2choice == p)
{
printf ("Player 1 wins");
}
else if (p1choice == s && p2choice == s)
{
printf ("Draw");
}
else if (p1choice == p && p2choice == r)
{
printf ("Player 1 wins");
}
else if (p1choice == p && p2choice == p)
{
printf ("Draw");
}
else if (p1choice == p && p2choice == s)
{
printf ("Player 2 wins");
}
printf ("%d", p1choice);
}
我需要使用枚举类型来获取每个玩家的输入。 这是一个简单的石头剪刀布游戏。 我的输出函数类型有问题,并且在函数调用中以及在函数体中分配 Choice p1choice 时出现以下错误。
Incompatible integer to pointer conversion passing 'int' to parameter of type 'int (*)()'
Thread 1: EXC_BAD_ACCESS (code=1, address = 0x0)
感谢您的意见和帮助!
【问题讨论】:
-
为了便于阅读和理解,请始终缩进代码。在每个左大括号 '{' 后缩进。在每个右大括号 '}' 之前取消缩进。
-
这一行:
output( getplayerone(), getplayertwo());可能会导致首先检索“playertwo”,因为标准中未定义参数评估的顺序,因此取决于实现 -
发布的代码包含许多随机空行的实例。为了可读性,最好通过空行分隔代码块(for、if、else、while、do...while、switch、case、default),而不是在函数体中放置其他/随机空行
-
如果通过
switch()语句而不是少量的if then else语句来测试choice1的内容会更加清晰和全面 -
变量
choice1int未初始化,并且(例如)如果用户输入Q,当它从对getplayerone()的调用返回时仍将未初始化,顺便说一句:最好是'lower camel case' 变量和函数名称,以提高可读性。这些相同的注意事项也适用于函数:getplayertwo()
标签: c function enums parameters