作者:喜欢香覀香的树花园 | 来源:互联网 | 2022-11-29 12:28
1> Kristjan Kic..:
回答你的问题.
我不建议打电话给主.
您可以创建另一个包含所有代码的函数.
在main中,您可以调用该函数.
你可以在该函数内调用一个函数(称为递归)
但是,一个简单的循环可以完成这项工作.
do{
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
float num1;
float num2;
float ans = 0.0;
char symbol;
char ask;
printf("Please type the expression you want to calculate: ");
if(scanf("%f%1s%f",&num1,&symbol,&num2) != 3)
{
printf("\nInvalid input! Please try again...\n\n");
}
else {
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if (num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
printf("\n");
}while(ask == 'y' || ask == 'Y') ;
printf("Thank you for using the program. Please give full marks.");
}
编辑:要回答对此问题的评论,您要做的是:
while(scanf("%f%1s%f",&num1,&symbol,&num2) != 3)
{
printf("\nInvalid input! Please try again...\n\n");
}
并删除 else
EDIT2:完整代码.请注意,表达式不能超过99个字符.
#include
int main()
{
float num1;
float num2;
float ans = 0.0;
char symbol;
char ask;
char string[100];
do{
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
printf("Please type the expression you want to calculate: ");
while(1){
fgets (string , 100 ,stdin);
if(sscanf( string, "%f%1s%f",&num1,&symbol,&num2)!=3)
printf("\nInvalid input! Please try again...\n\n");
else
break;
}
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if (num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
printf("\n");
}while(ask == 'y' || ask == 'Y') ;
printf("Thank you for using the program. Please give full marks.");
return 0;
}