字符串转浮点数

str转double

#include <iostream>
using namespace std;
double atof_my(const char* str){

    double res=0.0;
    double d=10.0;
    int jishu=0;
    bool flag=true;
    //检查空格 
    while(*str==' '){
        ++str;
    }
    //检查正负 
    if(*str=='-'||*str=='+'){
        if(*str=='-'){
            flag=false;
        }
        ++str;
    }
    if(!(*str>='0'&&*str<='9')){
        return res;
    }
    //检查小数点前数字 
    while(*str>='0'&&*str<='9'&&*str!='.'){
        res=res*10+(*str-'0');
        ++str;
    } 
    //小数点 
    if(*str=='.'){
        ++str;
    }
    //小数点后 
    while(*str>='0'&&*str<='9'){
        res+=(*str-'0')*1.0/d;
        d*=10.0;
        ++str;
    }
    //指数法表示 
    if(*str=='e'||*str=='E'){
        str++;
        if(*str=='+'){
            ++str;
            while(*str>='0'&&*str<='9'){
                jishu=jishu*10+*str-'0';
                str++;
            }
            while(jishu--){
                res*=10.0;
            }
        }
        if(*str=='-'){
            ++str;
            while(*str>='0'&&*str<='9'){
                jishu=jishu*10+*str-'0';
                str++;
            }
            while(jishu--){
                res/=10.0;
            }
        }
    }
    return res*(flag?1.0:-1.0);

}
int main() {
    char* cc=new char[100];
    while(1){
        cin>>cc;
        cout<<atof_my(cc)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/armstrong_rose/article/details/80470088
今日推荐