我转换了一个我知道如何用C语言在python中构造的代码,但是每次我在CodeBlocks中运行该程序时,该程序都会崩溃!而且我不知道为什么会这样,有人可以帮我吗?
该程序假定使用二进制搜索来猜测一个人的号码(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 100\n\n");
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?\n\n", 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;
}
我转换了一个我知道如何用C语言在python中构造的代码,但是每次我在CodeBlocks中运行该程序时,该程序都会崩溃!而且我不知道为什么会这样,有人可以帮忙...
您的二进制搜索不正确,您需要交换'h'和'l'的代码,并且因为您比较的是字符而不是字符串,所以请使用==而不是strcmp()。您不需要math.h,因为猜测是int,所以它是自动舍入的。您可以在scanf()之后使用getchar()清除缓冲区,并且需要在main之前在函数上声明