c - 求 0 到 125 之间的数的立方根

标签 c precision cubic

我正在尝试编写一个函数的 C 代码,该函数采用从 0125 的整数,并且仅当该整数为整数时才返回该整数的立方根( 1,2,3,4,5 ) 如果不是,则返回 0 。所以我写了这段代码:

unsigned int cubic(unsigned int n) {
    if (n > 125)
        return 0;
    double root = pow(n, (1 / 3.));
    double rem = (double)(roundf(root)) - root;
    if (rem != 0)
        return 0;
    else
       return roundf(root);
}

此函数适用于除数字 64125 之外的所有情况。 在这些情况下,它返回 0 而不是这些数字的立方根,它们分别是 45。 谁能向我解释为什么会这样?

最佳答案

因为 1/3. 不能准确表示为 float ,浮点计算 pow(64, (1/3.)) 可能会产生一个数非常接近 4,但稍微小一点或大一点,与 4 对于 (double)(roundf(root)) - root0 不同。

您可以通过这种方式解决这个精度问题:

unsigned int cubic(unsigned int n) {
    int root = (int)round(pow(n, 1 / 3.));
    if (root * root * root == n)
        return root;
    else
        return 0;
}

如果您的系统可用,您可以使用 cbrt(n) 而不是 pow(n, 1/3.),但精度问题可能仍然存在.

为了您的目标,迭代可能的整数根并检查似乎更简单:

unsigned int cubic(unsigned int n) {
    for (unsigned int i = 1; i <= 5; i++) {
        unsigned int i3 = i * i * i;
        if (i3 == n)
            return i;
        if (i3 > n)
            break;
    }
    return 0;
}

或者更明确:

unsigned int cubic(unsigned int n) {
    switch (n) {
      case 1 * 1 * 1: return 1;
      case 2 * 2 * 2: return 2;
      case 3 * 3 * 3: return 3;
      case 4 * 4 * 4: return 4;
      case 5 * 5 * 5: return 5;
      default: return 0;
    }
}

关于c - 求 0 到 125 之间的数的立方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72424049/

相关文章:

python - 求三次函数的根

javascript - 将分割三次贝塞尔曲线外推为 1,1

c - 为什么使用 memset 手动设置字节时字符串会缩短?

sql - MSSQL - 联合所有具有不同小数精度的

c - C 线程程序中的链接器错误..ld 返回 1 退出状态

Java 双加四舍五入

python - 为什么 QDoubleSpinBox 的精度有时高于其小数属性允许的精度?

python - 用 Python 进行样条插值

字符未保存到数组

c - 禁用 GDB 对 x86 异常的中断