主要代碼如下:
//擷取字元串的長度函數(每個漢字2個位元組長度)
int GetStringLength(string str)
{
int ret = 0;
int i = 0;
while (auto sss = str[i++] != '\0')
{
ret++;
}
return ret;
}
//double轉化為字元串函數
string DoubleToString(double d)
{
bool isNegative = d < 0 ? true : false;
double high, low;
if (isNegative)
{
high = std::ceil(d);
low = high - d;
}
else
{
high = std::floor(d);
low = d - high;
}
std::deque<int> intDeq, decDeq;
int h = (int)high;
if (isNegative)
{
h *= -1; //確定是非負數//
}
if (h < 10)
{
intDeq.emplace_front(h);
}
else
{
while (h > 0)
{
intDeq.emplace_front(h % 10);
h = std::floor(h / 10);
}
}
if (low > 0)
{
int tmp = 15; //確定小數點後15位//
while (low > 0 && tmp-- > 0)
{
decDeq.emplace_back(std::floor(10 * low));
low = 10 * low;
low -= std::floor(low);
}
}
else
{
decDeq.emplace_back(0);
}
std::string retVal;
retVal.resize(intDeq.size() + decDeq.size() + 2);
int i = 0;
for (const auto& e : intDeq)
{
retVal[i++] = e + 48;
}
retVal[i++] = '.';
for (const auto& e : decDeq)
{
retVal[i++] = e + 48;
}
if (isNegative)
{
retVal = "-" + retVal;
}
return retVal;
}
//字元串轉換為double函數
double StringToDouble(string str)
{
std::deque<int> intDeq, decDeq;
bool isFindDot = false;
int i = 0;
while (str[i] != '\0')
{
if (str[i] == '.')
{
isFindDot = true;
}
if (str[i] >= '0'&&str[i] <= '9')
{
auto ch = str[i] - 48;
if (isFindDot)
{
decDeq.emplace_back(ch);
}
else
{
intDeq.emplace_front(ch);
}
}
i++;
}
double retVal = 0.0;
i = 0;
for (const auto& e : intDeq)
{
retVal += e * std::pow(10.0, 1.0 * i++);
}
i = 1;
for (const auto& e : decDeq)
{
retVal += e * std::pow(10.0, (-1.0) * i++);
}
return retVal;
}
測試代碼如下:
int nLen = GetStringLength("a345阖家歡樂fF;$%^");
auto ff1 = StringToDouble(".12");
auto ff2 = StringToDouble("12.345");
auto ff3 = StringToDouble("123.45g.67Y");
auto ss1 = DoubleToString(12.345);
auto ss2 = DoubleToString(-16.10001);
cout << nLen << '\t' << ff1 << '\t' << ff2 << '\t'
<< ff3 << '\t' << ss1 << '\t' << ss2 << endl;
運作結果如下:
18 0.12 12.345 123.457 12.345000000000000