我无法确定如何存储用户输入的操作员。我认为我的第36行是导致我的问题的原因但不确定会发生什么(我确信你可以从代码中看到但我不能;))我是否进入第35行并将操作用于整数和命中输入没有任何反应我然后键入输入任何2个字母数字字符然后输入2个字母数字然后输入然后它吐出我的答案。我知道它可能很容易让我失踪。
此外,在我使该部分工作后,我想为用户添加“do while”循环以继续使用选择的运算符,直到iValue1!= 0
最后,使用“if”cin.fail阻止用户除以0的最简单方法是什么?如果是这样,我的第一个“如果”声明会出现吗?
*编辑:第35行=“cout<<”输入您要执行的操作:“
#include <iostream>
using namespace std;
int main()
{
float iValue1, iValue2, iValue3;
char chOperator1 = '/'; //Initializing operators
char chOperator2 = '*';
char chOperator3 = '+';
char chOperator4 = '-';
//Get user inputs
cout << "Enter the first value as an integer: ";
cin >> iValue1;
cout << "Enter the Second value as an integer: ";
cin >> iValue2;
cout << "Enter the operation you want to perform: ";
cin >> chOperator1 >> chOperator2 >> chOperator3 >> chOperator4;
if( chOperator1 == '/')
{
iValue3 = iValue1 / iValue2;
}
else {
if(chOperator2 == '*')
iValue3 = iValue1 * iValue2;
(chOperator3 == '+');
iValue3 = iValue1 + iValue2;
(chOperator4 == '-');
iValue3 = iValue1 - iValue2;
}
cout << "The result is \n " << iValue3;
return 0;
}
答案 0 :(得分:0)
我建议您使用数组或std :: vector进行多项操作:
char operations[4];
cout >> "Enter 4 operations: ";
for (unsigned int i = 0; i < 4; ++i)
{
cin >> operation[i];
}
for (unsigned int j = 0; j < 4; ++j)
{
const char opr = operation[j];
switch (j)
{
case '*':
cout << (iValue1 * iValue2) << "\n";
break;
case '/':
cout << (iValue1 / iValue2) << "\n";
break;
case '+':
cout << (iValue1 + iValue2) << "\n";
break;
case '-':
cout << (iValue1 - iValue2) << "\n";
break;
default:
cout << "Invalid operation, '" << oper << "'\n";
break;
}
}