C中基本的add / sub / mul / div程序有问题吗?

时间:2017-12-10 08:17:41

标签: c runtime-error

我正在尝试编写一个简单的程序,它输入两个浮点数和一个操作符号,并使用操作符号的ASCII值分支到特定的行并输出正确的答案。但是,程序不允许我输入第三个输入,操作符号,所以我得到的唯一输出是0.这是代码:

#include <stdio.h>
int main()
{
double x, y, answer;
char operation;


//enter the two operands which are held in x and y, respectively
scanf("%f %f", &x, &y);


//enter operation to be performed, ASCII value of operation (42 is *, 43 is 
//+, 45 is -, 47 is /) is stored in "operation" identifier
op:                    //label "op," not sure if I used this correctly
scanf("%c", &operation);


//if "+" was entered add x and y
if(operation=43){
    answer = x + y;
    printf("%.3f", answer);
}

//if "-" was entered subtract y from x
else if(operation=45){
    answer = x - y;
    printf("%.3f", answer);
}

//if "/" was entered divide x by y
else if(operation=47){
    answer = x / y;
    printf("%.3f", answer);
}

//if "*" was entered multiply x by y
else if(operation=42){
    answer = x * y;
    printf("%.3f", answer);
}

//if no valid operation entered rescan for valid operation
else goto op;

    return 0;
}

以下是控制台上显示的内容:

1
1
0.000
Process returned 0 (0x0)   execution time : 4.694 s
Press any key to continue.

如上所示,我无法指出我希望执行的操作。我确定这是一个简单的错误。是否有任何明显的错误可以指出给我,希望这个程序能够正常运行?

2 个答案:

答案 0 :(得分:3)

scanf("%c", &operation);将是

scanf(" %c", &operation);

这将确保我们不会消耗先前输入中的\n字符。 在您确实如此的情况下,您的operation变量保存值charcater \n' '中的scanf表示所有的空白字符都被消耗掉了。然后你得到正确的字符输入。

operation = 45也是operation == 45。更简单的说,你可以做到这一点

if( operation == '+')

之前您使用的是作业。你没有检查平等。 ==

此处您还使用了goto,可以轻松转换为while语句。在这里你不需要goto - goto创建一个更难调试的控制流。你可以在这里做到这一点。

do{
...



}while(operation!='+' || operation!='-'..);

   while(1){
   ...
    if( operation == '+' || operation == '-' ..)
        break;
   } 

答案 1 :(得分:1)

您需要在if语句中使用相等运算符。而不是thos“魔术”数字 - 使用字符

 if (operation=='+') { ....