Simple calculator program in C
我需要用C编写一个简单的程序,它可以简单地计算:+、-、*、。/
现在,我使用的是Visual Studio Express 2013,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include <stdio.h> #include <stdlib.h> int main(){ double a, b; double sum = 0; char o; //operator printf("Enter operator "); scanf_s("%c", &o); printf("Enter first operand "); scanf_s("%f", &a); printf("Enter second operand "); scanf_s("%f", &b); if (o == '+'){ sum = a + b; printf("The result is", &sum); } if (o == '-'){ sum = a - b; printf("The result is", sum); } if (o == '*'){ sum = a*b; printf("The result is", sum); } if (o == '/'){ if (b == !0){ sum = a / b; printf("The result is", sum); } else printf("Error"); } getchar(); } |
我的输出:输入运算符+输入第一个操作数三点五输入第二个操作数五点四
在我输入第二个数字之后——程序退出,什么也没有!没有编译错误,我也不知道该怎么做。有人能帮忙吗?
你没有正确使用
1 |
您没有在格式字符串中指定输出类型,而是传递要打印的变量的地址,而不是值。
你应该使用:
1 2 |
另外,您应该将
这里是我修改过的代码,它给出了正确的结果。我会指出我改了哪一行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include <stdio.h> #include <stdlib.h> int main(){ double a, b; double sum = 0; char o; //operator /* I had to use scanf, since I'm not using MS/Visual Studio, but GCC */ printf("Enter operator "); scanf("%c", &o); printf("Enter first operand "); scanf("%lf", &a); /* changed %f to %lf */ printf("Enter second operand "); scanf("%lf", &b); /* changed %f to %lf */ /* I prefer to use if ... else if ..., this is personal preference */ if (o == '+'){ sum = a + b; printf("The result is %lf ", sum); /* Changed, see original post */ } else if (o == '-'){ sum = a - b; printf("The result is %lf ", sum); /* Changed, see original post */ } else if (o == '*'){ sum = a*b; printf("The result is %lf ", sum); /* Changed, see original post */ } else if (o == '/'){ if (b != 0){ sum = a / b; printf("The result is %lf ", sum); /* Changed, see original post */ } else printf("Error"); } getchar(); return 0; } |