在此示例中,您將學(xué)習(xí)使用switch語句在C語言編程中創(chuàng)建一個(gè)簡單的計(jì)算器。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
該程序需要一個(gè)算術(shù)運(yùn)算符+, -, *, /和兩個(gè)操作數(shù)。然后,它根據(jù)用戶輸入的運(yùn)算符對兩個(gè)操作數(shù)執(zhí)行計(jì)算。
#include <stdio.h>
int main() {
char operator;
double first, second;
printf("輸入運(yùn)算符 (+, -, *,): ");
scanf("%c", &operator);
printf("輸入兩個(gè)操作數(shù): ");
scanf("%lf %lf", &first, &second);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
break;
//運(yùn)算符與任何case都不匹配
default:
printf("錯(cuò)誤!運(yùn)算符不正確");
}
return 0;
}輸出結(jié)果
輸入運(yùn)算符(+, -, *,): * 輸入兩個(gè)操作數(shù): 1.5 4.5 1.5 * 4.5 = 6.8
用戶輸入的*運(yùn)算符存儲在operator中。 并且,兩個(gè)操作數(shù)1.5和4.5分別存儲在first和second中。
由于運(yùn)算符*與 case '*':相匹配,因此程序的控制跳轉(zhuǎn)到
printf("%.1lf * %.1lf = %.1lf", first, second, first * second);該語句計(jì)算結(jié)果并將其顯示在屏幕上。
最后,break;語句結(jié)束該switch語句。