c - 如何将 char* 转换为带逗号(小数点)的数字函数?

标签 c pow

我编写了 change() 来帮助我将字符串转换为 double

例如:如果字符串是“5.5”,我希望数字是5.5。如果字符串是“0.0”,我希望数字是0。另一个例子:“50”到50。

现在的问题是,当我将 change() 与库 math.h 中的 pow() 一起使用时,一切正常,我用大量输入,一切都很完美。

测试示例:

change("5.0") 给我 5
change("1.5") 给我 1.5

因为我不能使用我编写的 power() 的库数学,但是当我测试 change() 时,现在我没有得到输出。我认为它陷入了无限循环。

这件事发生的原因有什么帮助吗?

double change(char* Point) {
    int count = 0;
    double res = 0;
    while (*Point == '0') {
        Point++;
    }
    while (*Point != '.' && *Point) {
        count++;
        Point++;
    }

    int num1 = 0;
    for (int i = 0; i < count; i++) {
        Point--;
        num1 = (*Point - '0') * (power(10, i));
    }

    int i = -1;
    while (*Point != '.' && *Point) {
        Point++;
    }
    double num2 = 0;
    if (!*Point) {
        return res = (double) num1 + num2;

    }
    Point++;
    while (*Point) {
        num2 = (double) (*Point - '0') * (double) (power(10, i));
        i--;
        Point++;
    }
    res = (double) num1 + num2;

    return res;
}

我还写了函数power:

int power(int base,int exp)
{
    int result=1;
    if(exp == 0){
        return 1;
    }
    while (exp != 0)
    {
        result=result*base;
        exp--;
    }
    return result;
}

最佳答案

因为你在 change 函数中调用了函数 power(10,i) ,而 i 是一个负值。您可以通过在幂函数中添加 if 语句来解决此问题

if (exp < 0) {
    exp = 0 - exp;
    return(1/power(base,exp));
}

编辑:您还必须更改幂函数以返回 double 而不是 int

关于c - 如何将 char* 转换为带逗号(小数点)的数字函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114348/

相关文章:

c - 在C中逐行读取文件

python - 在 C 中对 BlueZ 提供的文件描述符进行操作

javascript - 如何在 Math.pow(10, 10000000) 中获取整数

c++ - Pow() 计算错误?

C语言中从pow/powl到Long Long的类型转换值(value)

c - 释放非 malloc 的内存

c - 在 C 中将数组写入 .dat 文件

c - 带有连接参数的 X-Macro

c++ - 通过修改的exp最快的pow()替换。当已经计算出较低的幂时,通过平方