C++
编写程序,使其能读入并计算一个只包含加减运算的表达式,每一个输入的数据都是浮点数,除第一个数以外,
其余每个数前面都有一个运算符,表达式以分号“;”结束。
例如:
23+43-233+234;
输入输出格式要求:
要求输出小数点后6位。
只输出运算结果,请不要输出其他字符,遇到异常情况(如结尾不是分号等),输出error
例如:
输入:23+43-233+234;回车
输出:67.000000
输入:23+43,回车
输出:error
cout
的精度设置问题,需要更高精度可以选用 printf
或者用 cout << fixed << ...
之类的方式来提高输出精度
#include <iostream>
using namespace std;
double pow(double x, int k)
/* 快速幂,返回 x 的 k 次方 */
{
double ret = 1;
while(k)
{
if(k & 1)
ret = ret * x;
x = x * x, k >>= 1;
}
return ret;
}
string str;
int main()
{
cin >> str;
if(str[str.length() - 1] != ';')
{
cout << "error";
return 0;
}
double x = 0, ans = 0; /* x 为当前数字, ans 为当前位前所有运算的结果 */
bool dot = false, fh = true; /* dot 代表是否已经出现了'.', fh 代表当前项的系数 ( true 为 +, false 为 - ) */
int afd = 0; /* afd 代表当前是小数点后几位 */
for(auto& c : str)
{
if(c == '+' or c == '-')
{
ans += x * (fh ? 1 : -1);
afd = dot = (x = 0);
fh = c == '+' ? true : false;
}
else if(c == '.')
{
dot = true, afd = 1;
}
else if('0' <= c and c <= '9')
{
if(dot)
x = x + (c - '0') * pow(0.1, afd++);
else
x = x * 10 + c - '0';
}
else if(c != ';')
{
cout << "error";
return 0;
}
}
/* 将最后一项累加进结果 */
ans += x * (fh ? 1 : -1);
afd = dot = (x = 0);
cout << ans;
}