使用switch...case語句建立簡單的C++加減乘除計算器程式
讓我們來看一個用C++建立簡單計算器的程式,包含加、減、乘、除運算。
示例
#include <iostream> using namespace std; void calculator(int a, int b, char op) { switch (op) { case '+': { cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl; break; } case '-': { cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl; break; } case '*': { cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl; break; } case '/': { cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl; break; } default: cout<<"Invalid Input"<<endl; } } int main() { calculator(5,4,'+'); calculator(10,3,'-'); calculator(3,2,'*'); calculator(20,5,'/'); calculator(5,2,'?'); return 0; }
輸出
Sum of 5 and 4 is 9 Difference of 10 and 3 is 7 Product of 3 and 2 is 6 Division of 20 and 5 is 4 Invalid Input
在上面的程式中,使用了calculator函式來對兩個數字進行加、減、乘、除運算。這是使用switch case語句實現的。該函式接受三個引數:兩個要進行運算的數字和要執行的運算。如下所示:
void calculator(int a, int b, char op)
switch case語句中有四個case和一個default case。第一個case用於執行加法運算。兩個數字相加,並顯示它們的和。使用以下程式碼片段:
case '+': { cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl; break; }
第二個case用於執行減法運算。兩個數字相減,並顯示它們的差。使用以下程式碼片段:
case '-': { cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl; break; }
第三個case用於執行乘法運算。兩個數字相乘,並顯示它們的積。使用以下程式碼片段:
case '*': { cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl; break; }
第四個case用於執行除法運算。兩個數字相除,並顯示它們的商。使用以下程式碼片段:
case '/': { cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl; break; }
default case用於處理無效的運算子。使用以下程式碼片段:
default: cout<<"Invalid Input"<<endl;
calculator()函式在main()函式中被呼叫,用於執行不同的運算和使用不同的運算元。這由以下程式碼片段演示:
calculator(5,4,'+'); calculator(10,3,'-'); calculator(3,2,'*'); calculator(20,5,'/'); calculator(5,2,'?');
廣告