我想编写一个简单的计算器。计算在函数中。 我的问题是,结果总是0. :( 怎么了? 请看我的代码:
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
double addition(double a,double c);
double subtraktion(double a, double c);
double multiplikation(double a, double c);
double division(double a, double c);
int main()
{
double z=0, a, c;
char b;
printf("Insert your Numbers to calculate!");
scanf_s("%lf", &a);
scanf_s("%c", &b);
scanf_s("%lf", &c);
if (b == '+')
{
addition(a, c);
}
if (b == '-')
{
subtraktion(a, c);
}
if (b == '*')
{
multiplikation(a, c);
}
if (b == '/')
{
division(a, c);
}
printf("Result: %lf", z);
system("pause");
}
double addition(double a, double c)
{
double z;
z = a + c;
return(z);
}
double subtraktion(double a, double c)
{
double z;
z = a - c;
return(z);
}
double multiplikation(double a, double c)
{
double z;
z = a*c;
return(z);
}
double division(double a, double c)
{
double z;
z = a / c;
return(z);
}
我使用Visual Studio 2013进行编程。我尝试调试程序,但这不起作用。请原谅我的英语不好。
答案 0 :(得分:4)
您无法将操作结果分配给z
。而不是:
if (b == '+')
{
addition(a, c);
}
你应该做
if (b == '+')
{
z = addition(a, c);
}
同样适用于所有其他案例
答案 1 :(得分:2)
我尝试了这段代码并且运行正常:
#include <stdlib.h>
#include <stdio.h>
double addition(double a,double c);
double subtraktion(double a, double c);
double multiplikation(double a, double c);
double division(double a, double c);
int main()
{
double z=0, a, c;
char b;
printf("Insert your Numbers to calculate!");
scanf("%lf", &a);
scanf("%c", &b);
scanf("%lf", &c);
if (b == '+')
{
z = addition(a, c);
}
if (b == '-')
{
z = subtraktion(a, c);
}
if (b == '*')
{
z = multiplikation(a, c);
}
if (b == '/')
{
z = division(a, c);
}
printf("Result: %lf\n", z);
}
double addition(double a, double c)
{
double z;
z = a + c;
return(z);
}
double subtraktion(double a, double c)
{
double z;
z = a - c;
return(z);
}
double multiplikation(double a, double c)
{
double z;
z = a*c;
return(z);
}
double division(double a, double c)
{
double z;
z = a / c;
return(z);
}
编译然后输入类型:3 + 2 [按Enter键]它会显示确切的结果!
P.S。 我删除了'custom'标题,然后使用了简单的scanf函数。 我也删除了系统(“暂停”),因为我不在Visual Studio下。 (所以你可能需要那个)
所以我做的是:
- 删除了自定义标题#include“stdafx.h”
- 编辑scanf_s到scanf(...)
- 添加了z = functions()
- printf(... \ n)//没必要
它有效。