• 字符串函数---atof()函数具体解释及实现(完整版)


    atof()函数

    atof():double atof(const char *str );

    功 能: 把字符串转换成浮点数

    str:要转换的字符串。

    返回值:每一个函数返回 double 值。此值由将输入字符作为数字解析而生成。 假设该输入无法转换为该类型的值,则返回值为 0.0。

    函数说明 :atof()会扫描參数nptr字符串,跳过前面的空格字符。直到遇上数字或正负符号才開始做转换。而再遇到非数字或字符串结束时('')才结束转换,并将结果返回,str字符串可包括正负号、小数点或E(e)来表示指数部分。

    #include<iostream>
    
    using namespace std;
    
    double atof_my(const char *str)
    {
    	double s=0.0;
    
    	double d=10.0;
    	int jishu=0;
    
    	bool falg=false;
    
    	while(*str==' ')
    	{
    		str++;
    	}
    
    	if(*str=='-')//记录数字正负
    	{
    		falg=true;
    		str++;
    	}
    
    	if(!(*str>='0'&&*str<='9'))//假设一開始非数字则退出。返回0.0
    		return s;
    
    	while(*str>='0'&&*str<='9'&&*str!='.')//计算小数点前整数部分
    	{
    		s=s*10.0+*str-'0';
    		str++;
    	}
    
    	if(*str=='.')//以后为小树部分
    		str++;
    
    	while(*str>='0'&&*str<='9')//计算小数部分
    	{
    		s=s+(*str-'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>0)
    			{
    				s*=10;
    				jishu--;
    			}
    		}
    		if(*str=='-')
    		{
    			str++;
    			while(*str>='0'&&*str<='9')
    			{
    				jishu=jishu*10+*str-'0';
    				str++;
    			}
    			while(jishu>0)
    			{
    				s/=10;
    				jishu--;
    			}
    		}
    	}
    
        return s*(falg?-1.0:1.0);
    }
    
    int main()
    {
    	char *s1="  123.456567567e-10";
    	char *a1="  123.456567567e-10";
    	
    	char *s2="1234567.235e+10";
    	char *a2="1234567.235e+10";
    
    	char *s3="  123.456567567e-10";
    	char *a3="  123.456567567e-10";
    
    	double sum_1=atof_my(s1);
    	double sum1=atof(a1);
    
    	double sum_2=atof_my(s2);
    	double sum2=atof(a2);
    
    	double sum_3=atof_my(s3);//遇到''结束
    	double sum3=atof(a3);
    	
    	cout<<"atof_my:"<<sum_1<<endl;
    	cout<<"atof   :"<<sum1<<endl;
    
    	cout<<"atof_my:"<<sum_2<<endl;
    	cout<<"atof   :"<<sum2<<endl;
    
    	cout<<"atof_my:"<<sum_3<<endl;
    	cout<<"atof   :"<<sum3<<endl;
    	
    	system("pause");
    	return 0;
    }
    
    执行结果比較图:



  • 相关阅读:
    filter 静态资源
    getRequestURI,getRequestURL的区别
    基于NodeJs的网页爬虫的构建(二)
    基于NodeJs的网页爬虫的构建(一)
    Reverse Words in a String
    Sum Root to Leaf Numbers
    Search Insert Position
    Wildcard Matching
    Trapping Rain Water
    Gray Code
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/6937053.html
Copyright © 2020-2023  润新知