请编写程序,通过命令行参数接收“两个实数(x,y)和一个字符(ch)”(字符必须是‘+’、‘-’、‘*’、‘/’其中的一个),然后由程序计算并输出两数进行运算的相应结果, 格式为:x<运算字符>y=<运算结果>。例如:在命令行中输入 : 123 + 34,则程序输出: 123+34=157。 注意:如果命令行接收参数个数多于或小于4,则可以直接判定为输入错误,输出“Input error,end.”(输出内容不含双引号)。 【输入形式】 从命令行输入:“两个实数和一个字符”(字符必须是‘+’、‘-’、‘*’、‘/’其中的一个),数据间采用“空格”分隔(如:123 + 34)。 【输出形式】 输入正确时,输出:x<运算字符>y=<运算结果>。例如:在命令行中输入 : 123 + 34,则程序输出: 123+34=157; 输入错误时,输出“ERROR:Operator over bound.”(输出内容不含双引号); 分母为零(x/y运算时y=0)时,输出“ERROR:Zero donominator.”(输出内容不含双引号)。 【样例输入1】 123 + 456 【样例输出1】 123.000000+456.000000=579.000000 【样例输入2】 123 / 0 【样例输出2】 ERROR:Zero donominator. 【样例输入3】 2 B 3 【样例输出3】 ERROR:Operator over bound.,我要C++程序
时间: 2024-03-25 14:38:21 浏览: 20
以下是 C++ 的代码实现:
```cpp
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
double calc(double x, double y, char ch) {
if (ch == '+')
return x + y;
else if (ch == '-')
return x - y;
else if (ch == '*')
return x * y;
else if (ch == '/') {
if (y == 0) {
cout << "ERROR:Zero donominator." << endl;
exit(0);
}
else
return x / y;
}
else {
cout << "ERROR:Operator over bound." << endl;
exit(0);
}
}
int main(int argc, char *argv[]) {
if (argc != 4) {
cout << "Input error,end." << endl;
return 0;
}
double x, y;
char ch;
try {
x = stod(argv[1]);
y = stod(argv[2]);
ch = argv[3][0];
double res = calc(x, y, ch);
cout << fixed << setprecision(6) << x << ch << y << "=" << res << endl;
}
catch (...) {
cout << "Input error,end." << endl;
}
return 0;
}
```
在命令行中执行 `./calc 123 + 34`,即可得到输出:`123.000000+34.000000=157.000000`。