【问题标题】:I can't understand why this code give me wrong results for multiplication ,division and subtraction?我不明白为什么这段代码给我的乘法、除法和减法错误的结果?
【发布时间】:2020-02-27 04:27:55
【问题描述】:

我不明白为什么这段代码给我的乘法、除法和减法错误的结果? 它给我任何乘法运算的结果为零,任何除法错误的结果最后减法的结果总是1


#include <stdio.h>
long operations(char x,int num1 ,int num2 );

int main(void) {
    char x;
    int num1 , num2;
    long result;
    setbuf(stdout,NULL);
    result=operations(x,num1 ,num2 );

}
long operations(char x,int num1 ,int num2 )
{
    printf("please enter your operation sum (1) ,subtrcation(2),mul(3),div(4) :");
    scanf("%d",&x);

    if (x==(1||2||3||4))
    {
    printf("please enter the first and second numbers : \n ");
    scanf ("%d%d" ,&num1 ,&num2);
    }
    else
    {
        printf("error ") ;
    }

    switch (x)
    {
    case 1:
    {
        return  printf("the result  sum is  :%d ",(num1+num2)) ;

    }
    case 2:
    {
        return  printf("the result of subtraction  is :%d ",(num1-num2)) ;

    }
    case 3:
        {
            return  printf("the result multiblication is :%d ",(num1*num2)) ;

        }
    case 4:
        {
            return  printf("the result division  is :%d ",(num1/num2)) ;

        }




    }
}

【问题讨论】:

  • if (x==(1||2||3||4)) 与 if (x == 1) 相同。肯定是骗子
  • 编译器为此代码生成 8 个警告。使用 C 进行编程时,您需要启用警告(至少在 gcc 或 clang 中使用 -Wall -Wextra)、阅读警告并修复警告。

标签: c function


【解决方案1】:

你不能“重构”你的条件x==(1||2||3||4)

你需要显式写x == 1 || x == 2 || x == 3 || x == 4。

您的编译器理解“如果x 等于1 或者如果x 等于2 等”
它不理解“如果x 等于1、2、3 或4”

任何不为零的数字都被视为true,因此1||2||3||4 与1 相同。

如果你愿意,你可以写x &gt;= 1 &amp;&amp; x &lt;= 4。您只检查下限和上限。

另外,在除法的情况下,不要忘记检查num2 与0 是否不同。否则,您的程序将崩溃。

【讨论】:

  • 对 num2 == 0 导致 UB 的担忧适用于所有 4 个运算符,因为每个运算符都可能溢出(更多 UB)。
【解决方案2】:

正如@chux 已经提到的,这个if 语句总是正确的,因为true 表示!= 0。因此每个不等于0 的数字都会匹配条件。

@Haltarys 已经建议的解决方案的另一种方法是另一种 switch - 这可能会提高可读性:

switch(x)
{
case 1: // fallthrough
case 2: // fallthrough
case 3: // fallthrough
case 4:
    printf("please enter the first and second numbers : \n ");
    scanf ("%d%d" ,&num1 ,&num2);
    break;
default:
    printf("error ");
    // consider returning here instead of break because you have no return below for this case
    break;
}

由于这些情况与您的switch 中的情况相同,因此可能会考虑将它们结合起来。

关于您的代码的其他一些提示:

  • 考虑如果您的初始条件失败会发生什么 (x == 5 例如) - 然后您将打印错误消息但缺少default switch 的声明,因此缺少 return 值。您的编译器应该对此有所抱怨。
  • 您的除法不会打印您想要的结果,因为您打印了%d,这意味着该值被强制转换并且您不会打印十进制数字 - 而是使用%.2f 例如得到小数点后 2 位数字并转换 num1 以免得到 int 结果:(double)num1 / num2
  • 您返回的不是数学运算的结果,而是被调用的printf 的返回值,即打印的字符数。

【讨论】:

    猜你喜欢
    • 2012-05-23
    • 2014-06-12
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2016-08-22
    • 2022-12-18
    相关资源
    最近更新 更多