设为首页 加入收藏

TOP

浮点数字符串转换成浮点数实现(二)
2014-11-23 23:33:47 来源: 作者: 【 】 浏览:3
Tags:点数 字符串 换成 实现
------------------------------------------------------------

// 函数 : StrToFloatW

// 功能 : 将一个字符串转换为浮点数

// 返回值 : float

// 参数 : char* pstrfloat

// 附注 :

// -------------------------------------------------------------------------

float StrToFloatW(wchar_t* pstrfloat)

{

// check

if (!pstrfloat)

{

return 0.0;

}

bool bNegative = false;

bool bDec = false;

wchar_t* pSor = 0;

wchar_t chByte = L'0';

float fInteger = 0.0;

float fDecimal = 0.0;

float fDecPower = 0.1f;

// 进行首位判断,判断是否是负数

if (pstrfloat[0] == L'-')

{

bNegative = true;

pSor = pstrfloat + 1;

}

else

{

bNegative = false;

pSor = pstrfloat;

}

while (*pSor != L'\0')

{

chByte = *pSor;

if (bDec)

{

// 小数

if (chByte >= L'0' && chByte <= L'9')

{

fDecimal += (chByte - L'0') * fDecPower;

fDecPower = fDecPower * 0.1;

}

else

{

return (bNegative -(fInteger + fDecimal): fInteger + fDecimal);

}

}

else

{

// 整数

if (chByte >= L'0' && chByte <= L'9')

{

fInteger = fInteger * 10.0 + chByte - L'0';

}

else if (chByte == L'.')

{

bDec = true;

}

else

{

return (bNegative -fInteger : fInteger);

}

}

pSor++;

}

return (bNegative -(fInteger + fDecimal): fInteger + fDecimal);

}

// -------------------------------------------------------------------------

// $Log: $

测试用例:

// StringToFloatShell.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#include "StringToFloat.h"

int _tmain(int argc, _TCHAR* argv[])

{

float aaaa = 0;

aaaa = StrToFloat(L"12.34");

aaaa = StrToFloat(L"a23");

aaaa = StrToFloat(L"1234");

aaaa = StrToFloat(L"12.34");

aaaa = StrToFloat(L"12.34.56");

aaaa = StrToFloat(L".34");

aaaa = StrToFloat(L"34a");

aaaa = StrToFloat(L"34a.456");

aaaa = StrToFloat(L"-34");

aaaa = StrToFloat(L"-56.34");

aaaa = StrToFloat(L"-3.45.67");

aaaa = StrToFloat(L"-.45.6a");

aaaa = StrToFloat(L"-.");

aaaa = StrToFloat(L"-0");

return 0;

}

大家可以再找找BUG。

[END]

摘自 magictong的专栏

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇从C语言实战谈编程:hello world .. 下一篇C语言常见问题

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: