递归~逆波兰式

本文详细介绍了使用C++实现表达式解析的功能,并特别关注了如何将字符串转换为数字类型,通过使用标准库中的`atof()`函数进行转换。文章还讨论了在实际应用中可能遇到的问题及解决策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



代码:

#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*

同时欢迎提出宝贵意见,以帮助我改进,不胜感激!!!

——桑海整理


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值