所以我打算做一個簡單的數學公式,打印一個菜單,然後將操作符作爲char
。然後,它會提示用戶輸入兩個數字,然後打印出結果問題,然後以如下格式回答:10 + 20 = 30
。Switch語句中的C++數學
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
//Variables
char op_choice;
int usrnum_1;
int usrnum_2;
//Menu
cout << "Operator Menu\n\n";
cout << "+\n";
cout << "-\n";
cout << "*\n";
cout << "/\n";
cout << "%\n\n";
cout << "Choice:";
cin >> op_choice;
cout << "\nNumbers:";
cout << "\n\nEnter TWO numbers to complete an arithmitic operation with the " << op_choice << " operator: \n";
cout << "eg: 1 + 2 = 3\n";
cout << "\nNumber 1: ";
cin >> usrnum_1;
cout << "Number 2: ";
cin >> usrnum_2;
switch (op_choice)
{
case '+':
break;
case '-':
cout << "\nYou picked " << usrnum_1 << " - " << usrnum_2 << " = ";
cout << usrnum_1 - usrnum_2;
break;
case '*':
cout << "\nYou picked " << usrnum_1 << " X " << usrnum_2 << " = ";
cout << usrnum_1 * usrnum_2;
break;
case '/':
cout << "\nYou picked " << usrnum_1 << "/" << usrnum_2 << " = ";
cout << usrnum_1/usrnum_2;
break;
case '%':
cout << "\nYou picked " << usrnum_1 << " % " << usrnum_2 << " = ";
cout << usrnum_1 % usrnum_2;
break;
default:
cout << "\nYou made an illegal choice.\n";
}
cout << "\nYou picked " << usrnum_1 << " " << op_choice << " " << usrnum_2 << " = ";
cout << usrnum_1 << op_choice << usrnum_2;
getchar();
return 0;
}
其實我已經得到這個代碼的工作,你可以從減法和乘法等看到,但我希望得到開關塊之外COUT(我開始做,並加入了測試)。有沒有辦法做到這一點,而不是使原來的int成爲int?或者把cout語句放到switch塊中?使用if-else-if語句會更好嗎?
你爲什麼不只是有一個變量來存儲的答案?您已經存儲了操作員角色和用戶放入的值。在switch語句中,只需執行計算並存儲該值,然後僅使用一個cout打印輸出。 –
你的意思是你想在'switch'之外打印數學運算的結果嗎?如何將它存儲在一個變量並打印? –
其他評論的更一般的表述:將顯示結果的結果分開計算。 – molbdnilo