c语言 - 使用二进制搜索猜测一个人的秘密号码在 0 - 100 之间



我用 C 语言转换了一个我知道如何用 python 构建的代码,但每次我在 CodeBlock 中运行程序时,程序都会崩溃!我不知道为什么会这样,有人可以帮助我吗?

该程序假设使用二叉搜索来猜测一个人的数字(在 0 到 100 之间(。 例如,如果我的数字是 66,程序会询问我的数字是否是 50,因为 66 大于 50,数字 50 成为下边界,而 100 仍然是上限边界,依此类推......

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int x;
printf("Please think of a number between 0 and 100nn");
x = binarysearch();
printf("%d", x);

}
int binarysearch()
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
while (1){
guess = round(((hi + lo)/2));
printf("Is your secret number %d?nn", guess);
printf("Enter 'h' to indicate the guess is too high. nEnter 'l' to indicate the guess is too low.nEnter 'c' to indicate I guessed correctly. n");
scanf("%c", &user_inp);
if (strcmp(user_inp, "c") == 0){
break;
}
else if  (strcmp(user_inp, "h")==0){
hi = guess;
}
else if (strcmp(user_inp, "l")==0){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
continue;
}
}
printf("Game over. Your secret number was");
return guess;
}

根据评论,问题很可能是strcmp使用不正确:

char *string = "fish";
char not_a_string = 'f';
if (0 == strcmp( not_a_string, string  ))
...

字符'f'具有 ASCII 值0x66。strcmp会盲目地将其用作指针(期望它指向有效的字符串(,这将在您访问不属于您的内存时导致崩溃(分段错误(。

在这种情况下,你会侥幸逃脱strcmp( &not_a_string, string ),但这是好运,而不是正确的代码。

要将用户的字符输入与另一个字符进行比较,您可以使用简单的相等性(因为它们都是整数(:

if ( user_inp == 'c' ) ...

所以这是你的代码修复的,但是你最初是如何运行它的? 对我来说,GCC立即抱怨:

In function 'int binarysearch()': so.cpp:17:29: error: invalid conversion from 'char' to 'const char*' [-fpermissive] 
if (strcmp(user_inp, "c") == 0){

并且没有产生输出。 它告诉你我刚刚做的同样的事情(尽管有点隐晦(。

要吸取的教训:倾听编译器的抱怨(并尽可能让编译器抱怨(


@pmg还指出:

在转换说明符之前添加一个空格:scanf(" %c", &user_inp)

如果没有它,每次按 Enter 时:

Sorry, I did not understand your input.Is your secret number 25?

即你得到一个虚假的投诉。 但是有了空间,它可以根据需要工作。

(我讨厌scanf,所以不知道为什么这;)工作(

  1. 您的二进制搜索不正确,您需要交换'h''l'的检查。
  2. 因为您比较字符而不是字符串,所以请使用==而不是strcmp().
  3. 你不需要包括<math.h>因为猜测是一个int,所以它会自动舍入浮点数。
  4. 您可以使用getchar()scanf()后清除缓冲区
  5. 您需要在main之前声明函数(可能是通过在main之前定义函数(。
#include <stdio.h>
#include <stdlib.h>
// WITHOUT <MATH.H>
int binarysearch(void);
int main(void)
{
int x;
printf("Please think of a number between 0 and 100nn");
x = binarysearch();
printf("%d", x);
return 0;    // RETRUN 0    
}
int binarysearch(void)
{
int hi,lo,guess;
hi = 100;
lo = 0;
char user_inp;
int flag = 1;    // USE FLAG, NOT BREAK AND CONTINUE
while (flag){
guess = ((hi + lo)/2);   // WITHOUT ROUND
printf("Is your secret number %d?nn", guess);
printf("Enter 'h' to indicate the guess is too high. nEnter 'l' to indicate the guess is too low.nEnter 'c' to indicate I guessed correctly. n");
scanf("%c", &user_inp);
getchar(); // CLEAR THE BUFFER
if (user_inp == 'c'){   // MAKE FLAG 0
flag = 0;
}
//  USE '==', NOT STRCMP
else if  (user_inp == 'l'){  // YOU NEED TO SWAP 'L' & 'H'
hi = guess;
}
else if (user_inp == 'h'){
lo = guess;
}
else{
printf("Sorry, I did not understand your input.");
}
}
printf("Game over. Your secret number was ");
return guess;
}

最新更新