求问此处为什么有 syntax error :'type'报错?
此问题源于C Primer Plus第八章练习题第五题:使用更智能的猜测策略,使程序可以猜出1-100内的任意一个整数。
如:程序最初猜50,询问用户是猜大了、猜小了还是猜对了。如果猜小了,那么下一次猜测的值应是50和100中值,耶尔就是75。如果这次猜大了,那么下一次猜测的值应是50和75的中值,等等。使用二分查找(binary search)策略,如果用户没有欺骗程序,那么程序很快就会猜到正确的答案
#include
char get_choice(void);
char get_first(void);
int main()
{
int head=1;
int tail=100;
int guess=(head+tail)/2;
char ch;
printf("I will guess an integer from 1 to 100.\n");
printf("Please responde by Biger(B) or Lower(L) or Yes(Y).\n");
do
{
printf("Is your number is %d?\n",guess);
if((ch=get_choice())=='Y')
break;
if((ch=get_choice())=='B')
{
tail=guess-1;
guess=(head+tail)/2;
continue;
}
else if((ch=get_choice())=='L')
{
head=guess+1;
guess=(head+tail)/2;
continue;
}
while((ch=get_choice())!='Y');
printf("I know the answer!\n");
return 0;
}
char get_choice(void)
{
int ch;
ch=get_first();
while(ch!='B'&&ch!='L'&&ch!='Y')
{
printf("I can only know Biger or Lower or Yes.\n");
printf("Please try again!\n");
ch=get_first();
}
return ch;
}
char get_first()
{
int ch;
ch=getchar();
while(getchar()!='\n')
continue;
return ch;
}
在VC++6.0运行后会在第35行 char get_choice(void)处报错syntax error:'type'。想求问一下为什么会有这个报错?谢谢!
定义的两个函数不用加void,还有一些其他的错误都改好了,望采纳回答
#include<stdio.h>
char get_first()
{
int ch;
ch=getchar();
while(getchar()!='\n')
continue;
return ch;
}
char get_choice()
{
int ch;
ch=get_first();
while(ch!='B'&&ch!='L'&&ch!='Y')
{
printf("I can only know Biger or Lower or Yes.\n");
printf("Please try again!\n");
ch=get_first();
}
return ch;
}
int main()
{
int head=1;
int tail=100;
int guess=(head+tail)/2;
char ch;
printf("I will guess an integer from 1 to 100.\n");
printf("Please responde by Biger(B) or Lower(L) or Yes(Y).\n");
do
{
printf("Is your number is %d?\n",guess);
ch=get_choice();
if(ch=='Y')
break;
if(ch=='B')
{
tail=guess-1;
guess=(head+tail)/2;
continue;
}
else if(ch=='L')
{
head=guess+1;
guess=(head+tail)/2;
continue;
}}
while(ch!='Y');
printf("I know the answer!\n");
return 0;
}
29行while((ch=get_choice())!='Y');左侧少了个大括号}
把void去掉。
把函数声明里的void去掉,再把定义里的void也去掉,c语言里函数形参里的void可以省略
第 35 行的问题是因为 char get_choice(void) 函数中调用了自己,这是不允许的。
可以修改代码,将调用自己的代码改为调用 get_first() 函数:
if((ch=get_first())=='B')
此外第 39 行的条件判断 while(ch!='Y') 可能不是期望的结果,因为它将导致程序一直循环,直到输入的字符为 'Y' 为止。可能希望修改代码,使程序在输入 'B' 或 'L' 时继续循环:
while(ch!='B' && ch!='L');
仅供参考,望采纳,谢谢。