[英]Simple calculator program in C
我需要用 C 编写一个简单的程序来进行简单的计算:+,-,*,/
现在,我使用的是 Visual Studio Express 2013,代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf_s("%c", &o);
printf("Enter first operand\n");
scanf_s("%f", &a);
printf("Enter second operand\n");
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();
}
我的输出:输入运算符 + 输入第一个操作数 3.5 输入第二个操作数 5.4
在我输入第二个数字后 - 程序退出,什么也没有! 没有编译错误,我不知道该怎么做。 有人可以帮忙吗?
您没有正确使用printf
。 这就是你正在使用的。
printf("The result is", &sum);
您没有在格式字符串中指定输出类型,而是传递要打印的变量的地址,而不是值。
你应该使用:
printf("The result is %lf\n", sum);
%lf
指定要打印double
, \\n
添加换行符,然后传递变量sum
的值,而不是它的地址。
此外,您应该将if (b == !0){
更改为if (b != 0){
。 如果你留下你所放的东西,它相当于if (b == 1){
,这可能不是你想要的。
编辑这是经过我修改的代码,它给出了正确的结果。 我会指出我更改了哪些行
#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\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a); /* changed %f to %lf */
printf("Enter second operand\n");
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\n", sum); /* Changed, see original post */
} else if (o == '-'){
sum = a - b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '*'){
sum = a*b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '/'){
if (b != 0){
sum = a / b;
printf("The result is %lf\n", sum); /* Changed, see original post */
}
else printf("Error");
}
getchar();
return 0;
}
%f
格式读取双打。 你应该使用%lf
: scanf_s("%lf", &a);
printf("The result is %e", sum);
if (b == !0)
更改为if (b != 0)
现在它工作正常我对它做了一些改变
问题出在你的“scanf_s”和“%f”上
#include<stdio.h>
#include<stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%d", &a);
printf("Enter second operand\n");
scanf("%d", &b);
if (o == '+'){
sum = a + b;
printf(" The result is %d", sum);
}
if (o == '-'){
sum = a - b;
printf("The result is %d", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is %d", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is %d", sum);
}
else printf("Error");
}
getchar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.