我正在尝试通过执行计算器项目来练习c ++。我成功了 完成目标,但我认为有一种方法可以简化我的4 if语句。第五 如果状态我想做其他4在一行做什么。我没有得到错误 ';'在cout最后部分的变量之后。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
float first ;
float last ;
char op ;
cout << "Pick your first number.\n";
cin>>first;
cout << "Now pick your operator.\n";
cin>> op;
cout << "Time for the last number.\n";
cin>>last;
// if (op =='*'){ cout << first << op << last << "=" << first * last; };
// if (op =='/'){ cout << first << op << last << "=" << first / last; };
// if (op =='+'){ cout << first << op << last << "=" << first + last; };
// if (op =='-'){ cout << first << op << last << "=" << first - last; };
if (op){ cout << first << op << last << "=" << first op last; }
char f;
cin >> f;
return 0;
}
答案 0 :(得分:0)
虽然技术上@ tomriddle_1234是正确的,你不能做一种脚本结果,但你可以先计算并确保你只有一行输出,如:
float result
// this can also be implemented using switch
if (op == '*') {
result = first * last;
} else if (op == '/')
result = first / last;
// continue for other operators
if (op){ cout << first << op << last << "=" << result; }
这至少会减少重复次数。