所以我一直致力于一个只是命令行程序的项目。 我遇到的问题是我想要创建一个计算器。代码如下所示:
int calculator()
{
char oper[1];
double x, y;
x = 1;
y = 1;
printf("Starting calculator...\n\n");
printf("Input an operator you want to execute: ");
gets(oper);
if (strncmp(oper, "+", 1) == 0)
{
printf("\ncalculator works like this x + y =\n");
printf("input x value:\n");
scanf("%lf",x);
printf("input y value:\n");
scanf("%lf",y);
printf("%.1lf + %.1lf = %.1lf\n",x, y, x+y);
}
else if (strncmp(oper, "-", 1) == 0)
{
printf("\ncalculator works like this x - y =\n");
printf("input x value:\n");
scanf("%lf",x);
printf("input y value:\n");
scanf("%lf",y);
printf("%.1lf + %.1lf = %.1lf\n",x, y, x+y);
}
else if (strncmp(oper, "*", 1) == 0)
{
printf("\ncalculator works like this x * y =\n");
printf("input x value:\n");
scanf("%lf",x);
printf("input y value:\n");
scanf("%lf",y);
printf("%.1lf + %.1lf = %.1lf\n",x, y, x+y);
}
else if (strncmp(oper, "/", 1) == 0)
{
printf("\ncalculator works like this x / y =\n");
printf("input x value:\n");
scanf("%lf",x);
printf("input y value:\n");
scanf("%lf",y);
printf("%.1lf + %.1lf = %.1lf\n",x, y, x+y);
}
else
{
printf("Incorrect operator, please try again!\n");
}
}
根据一些示例和教程,它应该可以正常工作,而且确实如此。 但运行代码后问题就出现了。它可以正常工作,直到插入x值。在它之后出现错误:
program.exe中0x0f74f508(msvcr100d.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00000000。
我见过类似这样的问题,但没有一个真正给出修复。谢谢你的帮助!
答案 0 :(得分:0)
尝试将scanf("%lf",x);
替换为scanf("%lf",&x);