gpt4 book ai didi

c - 实现以下函数,将 float 的字符串表示形式转换为 double :

转载 作者:行者123 更新时间:2023-11-30 19:39:59 25 4
gpt4 key购买 nike

Implement the following function which converts a string representation of a floating-point number into a double:

double strToDouble(char[] str)

Your implementation should be able to properly handle strings such as:

  • “123456”
  • “-123.456”
  • “123.456e13”
  • “123.456e-13”

Any improperly formatted input strings should result in the value 0.0 being returned.

Hints and Suggestions:

  • Use the function strToInt above as a starting point.
  • Use if statements after the first loop to check for things like decimal points, e’s (for scientific notation exponents), and negative signs.
  • Use a separate loop to process things after a possible decimal point.
  • Use yet another loop to process possible exponent values after an e.

调用函数 strToDouble 后我是如何回答的

1)正确的输出应该是这样的:

123456
-123.456000
1234560000000000.000000
0.000000

2)为什么我们需要放[i + 2]和[i+1]?我是随机放的,但我没有对此进行解释。

-

double strToDouble(const char str[]) {
int i = 0, k = 10;
double result = 0, doubleValue, expValue = 0, resultDecimal = 0;
double exp = 1;

if (str[0] == '-')
{
i++;
}

while (str[i] >= '0' && str[i] <= '9')
{
doubleValue = str[i] - '0';
result = result * 10 + doubleValue;
i++;
}

if (str[i] == '.')
{
while (str[i + 1] >= '0' && str[i + 1] <= '9')
{
doubleValue = (str[i + 1] - '0');
resultDecimal = resultDecimal + doubleValue / k;
k *= 10;
i++;
}
}


if (str[i + 1] == 'e')
{
if (str[i + 2] == '-')
{
while (str[i + 3] >= '0' && str[i + 3] <= '9')
{
doubleValue = str[i + 3] - '0';
expValue = expValue * 10 + doubleValue;
i++;
}
for (k = 0; k < expValue; k++)
{
exp /= 10;
}
}
else
{
while (str[i + 2] >= '0' && str[i + 2] <= '9')
{
doubleValue = str[i + 2] - '0';
expValue = expValue * 10 + doubleValue;
i++;
}
for (k = 0; k < expValue; k++)
{
exp *= 10;
}
}
}

result = (result + resultDecimal) * exp;

最佳答案

Why we need to put [i + 2] and [i+1]?I put randomly, but i do not have explanation to that.

这些随机偏移会破坏您的代码。它适用于给定的示例,但如果您不指定句点而是指定指数(例如“1e3”),它就会中断,因为即使没有指定,您也会继承解析句点后尾数的代码的偏移量期间:

if (str[i] == '.') {
// parse mantissa, using i + 1 as index
}

if (str[i + 1] == 'e') // i + 1 may be one beyond the character you
// should be looking at.

只有当您确实找到一个字符时,才应该在句点之后前进当前字符:

if (str[i] == '.') {
i++; // step over period
// parse mantissa, using i as index
}

if (str[i] == 'e') {
i++; // step over 'e'
// parse exponent, using i as index
}

同样的情况也适用于跨过符号 + (你似乎根本不处理它)和 - (你检测到,但不考虑它)在结果中)。

换句话说:您当前正在检查的字符应始终位于索引 i 处。你可以向前看,但只能在上下文中。当您向前看时,您还应该确保您看到的字符不在可能的空终止符之后。

关于c - 实现以下函数,将 float 的字符串表示形式转换为 double :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35955729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com