代码:
#include<iostream>
#include<string>
#include<cstdlib>
#include<iomanip> //格式控制
using namespace std;
double exp()
{
string str;
cin >> str;
switch(str[0])
{
case'+':
return exp() + exp();
case'-':
return exp() - exp();
case'*':
return exp() * exp();
case'/':
return exp() / exp();
default:
return atof(str.c_str());
}
}
int main()
{
cout << setiosflags(ios::fixed);
cout << setprecision(6) << exp() << endl; //精度设为6
return 0;
}
运行结果:
Enter strings:
* + 11.0 12.0 + 24.0 35.0
1357.000000
Process returned 0 (0x0) execution time : 3.380 s
Press any key to continue.
遇到问题:再用atof()函数转换str返回stdouble时,发现用atof(str)错误提示:
.cpp|22|error: cannot convert 'std::string' to 'const char*' for argument '1' to 'double atof(const char*)'|
网上搜索知道原来需要
atof的函数原形是:
double atof( const char *string );
即:string类操作的是char*,c_str()返回char* 的地址所以要用c_str()把string 类型的参数转化成const char * ,因为C++会对参数作严格的检查。
c_str()返回string类里的char*
同时欢迎提出宝贵意见,以帮助我改进,不胜感激!!!
——桑海整理