我已经使用成功的switch语句创建了一个简单的计算器程序。但是我在底部创建一个do while循环时遇到了麻烦,它循环了我试图创建的计算器函数,这是我的主要目标,询问用户是否要使用do while循环重复计算器程序。任何帮助,不胜感激。
#include <stdio.h>
char math;
float number1;
float number2;
void calculator();
int selection = 0;
int main()
{
void calculator(){
printf(" enter the math operation: ");
scanf("%c", &math);
printf("Enter two numbers: ");
scanf("%f%f", &number1, &number2);
switch(math)
{
case '+':
printf("number1+number2=%.2f",number1+number2);
break;
case '/':
printf("number1/number2=%.2f",number1/number2);
break;
case '-':
printf("number1-number2=%.2f",number1-number2);
break;
case '*':
printf("number1*number2=%.2f",number1*number2);
break;
default:
printf ("Wrong character entered.");
}
}
启动do while功能,询问用户是否要重复该程序。
do{
printf{"\n\n - Do you want to repeat the program?"};
printf("\n1 - Yes");
printf("\n2 - No");
scanf("%i", &selection );
}
while (selection != 2);
calculator();
return 0;
}
答案 0 :(得分:1)
要回答主要问题,您希望始终先在循环内运行计算器,然后再请求再次运行:
void calculator() {
// calc stuff here
}
int main() {
do {
calculator();
printf("\n\n - Do you want to repeat the program?");
printf("\n1 - Yes");
printf("\n2 - No");
scanf("%i", &selection );
} while (selection != 2);
}
答案 1 :(得分:1)
void calculator(){
及其正文移至main()
之外。 2 始终检查scanf()
的结果。
3在%c
之前插入空格以使用以前的EOL。
scanf(" %c", &math);
。
4按照@Josh B&amp; S的建议,将calculator();
移动到`while循环中@koodawg
答案 2 :(得分:1)
首先,我建议在函数main()
之外加上calculator()函数的定义其次,我建议尽可能不使用全局变量。只需将selection
变量的声明放入函数main(),并将math, number1, number2
变量声明放入函数计算器()
第三个(这个实际上回答了你的问题),在do {} while循环中调用函数calculator()
答案 3 :(得分:0)
你打电话给计算器是在错误的地方,你需要;
do {
calculator();
...
} while(sel != 2);
答案 4 :(得分:0)
你对计算器的调用是放在while中的。但是,它应该放在do中。因为,do stmt在while.so之前执行,如果你在do循环中调用calculator()函数是好的