简体   繁体   English

为什么我的代码只返回一个函数?

[英]Why is my code returning only one function?

I am new to Programming (starting with C), and tried to practice functions by building a calculator. 我是编程的新手(以C开头),并尝试通过构建计算器来练习函数。 But it only ever returns me the same function even though its If-Statement is not being called. 但是,即使没有调用其If-Statement,它也只会返回相同的函数。 This is my code: 这是我的代码:

#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;



}

I would really appreciate every bit of advice i can get! 我真的很感激我能得到的每一个建议!

This here 这里

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

Needs to be changed to 需要更改为

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

Because as it is, 'M' || 'm' 因为按原样, 'M' || 'm' 'M' || 'm' just turns into 1 , which is then assigned to Math , and that result is returned, which means the if is taken. 'M' || 'm'变成1 ,然后将其分配给Math ,并返回结果,这意味着采用if With this change, you're actually comparing Math to 'M' , and if it's not equal, to 'm' . 进行此更改后,您实际上是将Math'M'进行比较,如果不相等,则将其与'm'

Likewise for else if(Math = 'A' || 'a') and so on. 同样,对于else if(Math = 'A' || 'a')等。

note (=) is diffrent from (==) 注意 (=)与(==)不同

= is assignment operator it assigns the value in your code you are assigning the value 'M' to Math and logical operators return either 0 or 1. in this case, it returns 1 since 1 is returned control flows inside if and the result of the multiplication is obtained as output =是赋值运算符,它会在您将代码“ M”分配给Math的代码中赋值,逻辑运算符返回0或1。在这种情况下,它返回1,因为1和if的结果在内部返回了控制流。获得乘法作为输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM