为什么我的计算器的计算结果 return 不正确?

Why does my calculator function not return the correct result?

我是 C 编程语言的新手。我正在创建一个简单的计算器程序,但由于某种原因我的函数没有返回正确的结果。这是我的程序:

#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <string.h>


int calculator(int x, char operator, int y);
int main()
{
    int x;
    char operator;
    int y;

    printf("Enter an arithmetic experession: ");
    scanf("%d%s%d", &x, &operator, &y);

    int result = calculator(x, operator, y);

    if(result == -1)
    {
        printf("Error! Try again!");
    }
    else
    {

        printf("%d", result);
    }
    return 0;


}
int calculator(int x, char operator, int y)
{
    int result = 0;
    if(y = 0)
    {
        return -1;
    }

    if(operator == '+')
    {
        result = x + y;
    }
    else if(operator == '-')
    {
        result = x - y;
    }
    else if(operator == '*')
    {
        result = x * y;
    }
    else if(operator == '/')
    {
        result = x / y;
    }
    else if(operator == '%')
    {
        result = x % y;
    }
    else
    {
        return -1;
    }

    return result;


}

所以当我运行这个程序时,它要求一个算术表达式。如果我输入 5 + 3,它只有 returns 5!经过几次测试后,它似乎只是 returns 第一个操作数,无论如何。我想这是非常小的事情,但我看不出我错过了什么。

两个问题。第一个是您在表达式中阅读的位置:

scanf("%d%s%d", &x, &operator, &y);

operatorchar 但您使用的是用于字符串的 %s 格式说明符。这最终将运算符放入 operator,但随后将 NULL 终止符添加到内存中的下一个字节。由于此字节不是 operator 的一部分,这会导致未定义的行为。

您想使用 %c 代替读取单个字符。

第二个是您对 y:

进行零检查的地方
if(y = 0)

这是作业,不是比较。值 0 分配给 y,然后 y 被评估为布尔值,最终为 false。这就是为什么所有表达式的计算结果都好​​像 y 是 0.

将此更改为作业:

if(y == 0)