【发布时间】:2018-11-19 10:26:27
【问题描述】:
#include <stdio.h>
int main()
{
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");
/* want to restart main() again here */
}
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);
if (ask == 'y' || ask == 'Y') {
printf("\n");
main();
}
else {
printf("Thank you for using the program. Please give full marks.");
}
}
return 0;
}
【问题讨论】:
-
欢迎来到 stackoverflow.com。请花一些时间阅读the help pages,尤其是名为"What topics can I ask about here?" 和"What types of questions should I avoid asking?" 的部分。也请take the tour 和read about how to ask good questions。最后请阅读this question checklist。
-
至于“重复”某事,使用循环。
-
@John Hunter。你知道编程中的循环吗?另外,你知道递归吗?因为您似乎正在尝试将递归用于简单循环就足够的事情
-
@JohnHunter 我明白你需要做什么,但我需要知道你是否首先知道循环以便解释。 Kristjan Kica 的回答似乎还不错
标签: c