c - 用C程序编写具有一定约束的GUESS游戏。发生的问题-代码错误,代码逻辑,建议

标签 c recursion syntax-error logic

问题:

编写一个猜测游戏,用户必须猜测一个 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/

相关文章:

c - 使用套接字通信在 stdout 上打印的剩余字符

c++ - 程序地址范围

c - 删除带有结构元素的单链表

matlab - Matlab ode45基本设置

python - Python列表,列表项中间有空格

Prolog 运算符预期错误

c - 将数组分成两部分,对每个部分进行排序,然后重新组合成单​​个数组

可以在具有 32Kb 内存的 8 位设备上实现 RSA 加密吗?

python - 斐波那契数列的递归

java - Java中基于ArrayList的二叉树实现