【问题标题】:Why is my code returning only one function?为什么我的代码只返回一个函数?
【发布时间】:2019-01-25 09:00:44
【问题描述】:

我是编程新手(从 C 开始),并尝试通过构建一个计算器来练习函数。但即使没有调用它的 If-Statement,它也只会返回相同的函数。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int result;
int multiplication(int num1, int num2){

    result = num1 * num2;
    return result;
};

int addition(int num1, int num2){

    result = num1 + num2;
    return result;
};

int substraction(int num1, int num2){

    result = num1 - num2;
    return result;
};

int main(){
    int num1;
    int num2;
    char Math;

    printf("Do you want to do a Multiplication or an Addition, or a Substraction: ");
    scanf("%c", &Math);
    printf("Now give me a Number: ");
    scanf("%d",&num1);
    printf("Now give me another Number: ");
    scanf("%d",&num2);

    if(Math = 'M' || 'm'){
        printf("Your Mulitplication came out to %d", multiplication(num1,num2));
}
    else if(Math = 'A' || 'a'){
        printf("Your Addition came out to %d", addition(num1, num2));
}
    else if(Math = 'S' || 's'){
        printf("Your Substraction came out to %d", substraction(num1, num2));
}
    else{
        printf("Your Input was wrong");
};

return 0;



}

我非常感谢我能得到的每一个建议!

【问题讨论】:

  • 我发现了一些东西。 1)“=”是一个赋值运算符。您想在 if 语句中使用“==”。 2) 比较 Var 是 'X' 还是 'Y' 你需要做 "Var== 'X' || Var == 'Y'
  • 这些对于初学者来说是非常常见的错误,并且经常出现在这里 - 例如。 :If statements not working?Why is if statement not working
  • 您应该始终在编译器中启用警告。对于 GCC,您可以使用 -Wall -Wextra。这可能会向您显示一些警告“条件分配”或类似的。请始终注意所有警告。

标签: c function


【解决方案1】:

这里

if(Math = 'M' || 'm')

需要改成

if((Math == 'M') || (Math == 'm'))

因为原样,'M' || 'm' 只是变成了1,然后分配给Math,并返回结果,这意味着if 被占用。通过此更改,您实际上是在将 Math'M' 进行比较,如果不相等,则将其与 'm' 进行比较。

else if(Math = 'A' || 'a') 等也是如此。

【讨论】:

  • 第二个“M”应该是小“m”,但很清楚你的意思。
  • @visibleman 感谢您指出这一点。我刚刚注意到我犯了两次这个错误——一次在代码中,一次在解释中。
【解决方案2】:

注意 (=) 不同于 (==)

= 是赋值运算符,它将代码中的值分配给 Math,逻辑运算符返回 0 或 1。 在这种情况下,它返回 1 因为 1 返回了 if 内部的控制流 并得到相乘的结果作为输出

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 2021-10-28
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多