我不知道如何存储用户输入的操作符。我认为我的第36行是什么导致了我的问题,但不确定,所以发生了什么(我确信你可以从代码中看到,但我不能;))是我到第35行,把操作用于整数,点击输入,什么都没有发生,然后我输入任何2个字母数字字符,点击输入,然后2个字母数字,然后输入,然后它吐出我的答案。我知道可能是我错过了一些很容易的东西。
同样,在我得到那部分工作后,我想添加一个"do while"循环,让用户继续使用所选择的任何操作符,直到iValue1 !=0
最后,使用"if"来防止用户除以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;
}
我建议您使用数组或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;
}
}