问题:
编写一个猜测游戏,用户必须猜测一个 secret 号码。每次猜测之后,程序都会告诉用户他们的数字太大还是太小。最后应打印所需的尝试次数。如果他们连续多次输入相同的数字,则仅算作一次尝试。
我的代码:
#include<stdio.h>
#include<stdlib.h>
int compare(int m) {
int b;
b=73-m; ///I chose my number as 73 here.
if (b=0) printf("Congrats, you won.");
else {
if (-5 < b < 5) printf("Very Close\n"); ///always gives me this output two times.
else {
if (-15 < b < 15) printf("Close");
else {
printf("You are far");
}
}
}
return b;
}
int main() {
int arr[100],guess,count=0,i,m; ///I have 99 tries.
arr[0]=0;
for(i=1 ; i<=100 ; i++) {
printf("Enter your guess\n");
scanf("%d",&guess);
if(guess==arr[i-1]) {
arr[i]=guess;
printf("Guess is same as the previous input.\n");
} else {
arr[i]=guess;
compare(guess);
if (m = compare(guess)) {
count=count+1; /// can i create a separate function to keep the count?
printf("%d is the number of tries.\n",count);
break;
} else {
printf("\n");
}
}
}
return 0;
}
这总是给我两次相同的输出,即“非常接近非常接近”。我认为这是错误的代码(语法)或错误的逻辑。我也想通过代码来了解更好的算法/逻辑来解决这个问题(可能更短)。最后,我刚开始使用C作为第一语言进行编程。
最佳答案
条件-5 < b< 5
等于(-5 < b) < 5
,这意味着您将0
的 bool(boolean) (1
或-5 < b
)结果与5
进行了比较。
如果需要将b
与某个范围进行比较,则需要执行-5 < b && b < 5
。即明确比较b
与范围的两端。
另外,b = 0
是分配的不能比较,您需要使用==
进行比较。
关于c - 用C程序编写具有一定约束的GUESS游戏。发生的问题-代码错误,代码逻辑,建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755120/