C語言寫出來的簡單計算器
do…while無限回圈中套入switch
#include<stdio.h>
int main(void)
{
char operator;
int esc;
double a, b, c;
do
{
printf("請輸入運算子。\n");
printf("提醒:按q鍵退出計算器\n");
scanf_s(" %c", &operator, 1);
if (operator == 'q') {
return (1);
}
if (operator != '+' && operator != '-' && operator != '*' && operator!='/') {
printf("運算子錯誤,請重新輸入ー\n");
continue;
}
printf("請輸入數位。\n");
scanf_s("%lf%lf", &a, &b);
esc = 1;
switch (operator)
{
case '+':
c = a+b;
break;
case '-':
c = a-b;
break;
case '*':
c = a*b;
break;
case '/':
if (b == 0) {
printf("錯誤:除數不能爲0\n");
esc = 0;
break;
}
c = a/b;
break;
}
if (esc != 0) {
printf("%lf%c%lf = %g\n", a, operator, b, c);
}
} while(1);
return 0;
}