我只是想用C语言制作一个计算器。当我使用加法和减法时,程序运行良好,但是,当我尝试除法或乘法时,无论我提供什么输入,程序都将返回错误。
这是我的代码。在这种情况下,我只是简单地使用goto
语句而不是循环来进行多个用户输入(例如1 + 2 + 3 + ....)的循环b
,然后将先前的值保存回变量,然后询问另一个值并保存在variable中c
。
我只是想不出我的错误,任何帮助将不胜感激。
#include <stdio.h>
int main() {
int a, d;
double b=0,c=0;
printf("This is a CLI Based calculator program!\nSelect what do you want to do?!");
Restart: //If user still want to continue with current results
printf("\n1: Addition\t\t2: Subtraction\n3: Multiplication\t4: Divide\n");
printf("\nChoose option:");
scanf("%d",&a);
//Check if user has previously used the program or not
if(b==0) {
printf("Enter First Number: ");
scanf("%d",&b);
} else {
printf("\nYour Previous result is :%d", b);
printf("\nEnter Another Number: ");
scanf("%d",&c);
goto Continue;
}
printf("Enter Second Number: ");
scanf("%d",&c);
Continue: //Resume process from here if user wants to continue
switch (a) {
case 1:
printf("This is Addition: %d\n", b+c);
b = b+c;
break;
case 2:
printf("This is subtraction: %d\n", b-c);
b = b-c;
break;
case 3:
printf("This is Multiplication: %d\n", b*c);
b = b*c;
break;
case 4:
printf("This is division: %d\n", b/c);
b = b/c;
break;
default:
printf("Oops! Seems like you entered wrong option, Select Again!");
goto Restart;
}
//Check if User want to continue with previous result or not
printf("Do you want to continue?\n1: Yes\t\t2: No!\n");
printf("\nChoose option:");
scanf("%d",&d);
if (d==1){
goto Restart;
}
else {
printf("\nThank You! For using the calculator.");
}
return 0;
}
您的线路scanf("%d",&b);
(以及其他类似线路)是错误的。要读入一个double
值,您需要使用%lf
格式说明符(%d
用于十进制整数)。
因此,将其更改为scanf("%lf",&b);
(并根据需要在其他位置进行等效更改),然后重试。
因为printf
你有同样的问题。在这里printf("This is Multiplication: %d\n", b*c);
使用%d
是错误的。使用%f
打印双。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句