您的位置:首页 > 其它

字符串转化为数字 aotf

2015-07-24 15:15 267 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/lingzhu111/article/details/47041657

#include <iostream>
using namespace std;




float str2num(char *p){
    float tmp = 0.0;
    int dot = 0;
    float n = 1.0;
    const char *str = p;
    if (*str == '-' || *str == '+'){
        str++;
    }
    while(*str != 0){
        if(dot == 0){
            if(*str <= '9' && *str >= '0'){
                tmp = tmp*10 + ((*str) - '0');
            } else if (*str == '.') {
                dot = 1;
            } else {
                break;
            }
        } else {
            if(*str <= '9' && *str >= '0'){
                n = n*10;
                tmp +=  ((*str) - '0')/n;
            } else {
                break;
            }
        }
        str++;
    }
    if (*p == '-'){
        tmp = -tmp;
    }
    return tmp;
}




int main(){
    float n=0.0;
    char p[50]="";
    cin.getline(p,20);
    n = str2num(p);
    cout <<  n << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: