![](/img/trans.png)
[英]How to Fix the Logic Errors in My “Guess the Movie” Game as a C Program
[英]C program to write a GUESS game with certain constraints. Problems occuring - error in code, logic of code, suggesstions
題 :
編寫一個猜謎游戲,用戶必須猜出一個秘密數字。 每次猜測后,程序都會告訴用戶他們的數字是太大還是太小。 最后應該打印所需的嘗試次數。 如果他們連續多次輸入相同的數字,則僅計為一次嘗試。
我的代碼:
#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
或1
)的結果-5 < b
用5
。
如果需要將b
與范圍進行比較,則需要執行-5 < b && b < 5
。 即明確地將b
與范圍的兩端進行比較。
此外, b = 0
是賦值而不是比較,您需要使用==
進行比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.