通過編程,實現atof函數

相關知識:

頭文件:#include <stdlib.h>

函數 atof() 用於將字符串轉換爲雙精度浮點數(double),其原型爲:
double atof (const char* str);

atof() 的名字來源於 ascii to floating point numbers 的縮寫,它會掃描參數str字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數來檢測),直到遇上數字或正負符號纔開始做轉換,而再遇到非數字或字符串結束時('\0')才結束轉換,並將結果返回。參數str 字符串可包含正負號、小數點或E(e)來表示指數部分,如123. 456 或123e-2。

【返回值】返回轉換後的浮點數;如果字符串 str 不能被轉換爲 double,那麼返回 0.0。

程序如下:

#include <iostream>

using namespace std;

double myatof(const char* str)
{
	double result = 0.0;
	double d = 10.0;
	int count = 0;
	
	if(str == NULL)
		return 0;
	while(*str == ' ' || *str == '\t')
		str++;
	
	bool flag = false;
	while(*str == '-')  //記錄數字正負
	{
		flag = true;
		str++;
	}
	if(!(*str >= '0' && *str <= '9'))  //非數字退出
		return result;
		
	while(*str >= '0' && *str <= '9')  //計算小數點前面的部分
	{
		result = result*10 + (*str - '0');
		str++;
	}
	
	if(*str == '.')  //小數點
	    str++;
		
	while(*str >= '0' && *str <= '9')  //小數點後面的部分
	{
		result = result + (*str - '0')/d;
		d*=10.0;
		str++;
	}
	
	result = result * (flag ? -1.0 : 1.0);
	
	if(*str == 'e' || *str == 'E')  //科學計數法
	{
		flag = (*++str == '-') ? true : false;
		if(*str == '+' || *str == '-')
			str++;
		while(*str >= '0' && *str <= '9')
		{
			count = count*10 + (*str - '0');
			str++;
		}
		
		if(flag == true)            //爲-
		{
			while(count > 0)
			{
				result = result/10;
				count--;
			}
		}
		
		if(flag == false)  //爲+
		{
			while(count > 0)
			{
				result = result*10;
				count--;
			}
		}
	}

    return result;	
}

int main()
{
	char *s1 = "123.456hfid";
	char *s2 = "-12.45de";
	char *s3 = "ds24.67";
	char *s4 = "12.34e5ji";
	char *s5 = "13.56e-2hu";

	printf("result = %f\n",myatof(s1));
	printf("result = %f\n",myatof(s2));
	printf("result = %f\n",myatof(s3));
	printf("result = %f\n",myatof(s4));
	printf("result = %f\n",myatof(s5));

    return 0;
}

 運行結果如圖所示:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章