在C#中使用System.Math.Pow()方法查找数字的立方根 [英] Find Cube root of a number Using System.Math.Pow() method in C#

查看:83
本文介绍了在C#中使用System.Math.Pow()方法查找数字的立方根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写程序时,我遇到了在我的一个函数中找到数字的立方根的情况.

While writing a program I came across finding the cube root of a number in one of my functions.

当我使用以下代码时,我得到的立方根值不正确(为 n = 64 打印了 1 ).

when I used the below code, I was getting an incorrect value for the cube root (1 was getting printed for n = 64).

public static void cubicPairs(double n)
{
    double root = (System.Math.Pow(n, (1/3)));
    Console.WriteLine(root);
}

现在我将代码稍作更改后,

Now after I changed the code slightly to this,

public static void cubicPairs(double n)
{
    double root = (System.Math.Pow(n, (1.0/3.0))); //Changed how second parameter is passed
    Console.WriteLine(root);
}

我在调试时得到了 root = 3.9999999999999996 ,但是该方法正在打印 4 (这是正确的).

I got root = 3.9999999999999996 (while debugging) but the method was printing 4 (which is correct).

为什么两个值之间存在差异,以及是否与 System.Math.Pow()方法的第二个参数(即 1.0/3.0 (这是一个递归值),我应该使用什么来查找多维数据集根,以便在调试时获得 4 (而不是 3.9999999999999996 ?)?

Why is there a difference between the two values and if this has to do with the second parameter to the System.Math.Pow() method (i.e, 1.0/3.0 which is a recursive value), what should I use to find cube root so that I get 4 (while debugging) rather than 3.9999999999999996?

推荐答案

这是{花括号语言}中的标准陷阱,包括C#,带有整数操作数的除法将作为整数执行除法,而不是浮点除法.它总是产生整数结果, 1/3 产生0.将任何数字提高到0的幂都会产生1.0

This is a standard trap in the { curly brace languages }, C# included, a division with integral operands is performed as an integer division, not a floating point division. It always yields an integer result, 1 / 3 produces 0. Raising any number to the power of 0 produces 1.0

您可以通过将操作数之一转换为double来强制进行浮点除法.类似于 1.0/3 (double)integerVariable/3 .

You force a floating point division by converting one of the operands to double. Like 1.0 / 3 or (double)integerVariable / 3.

与乘法类似的问题,但通常较少陷阱,整数操作数会产生有溢出风险的整数结果.否则,这反映了处理器的工作方式,它具有针对这些操作的不同指令,即IMUL vs FMUL和IDIV vs FDIV.后者以奔腾处理器中的错误而闻名:)

Similar problem with multiplication, but usually less of a trap, integral operands produce an integral result that risks overflow. This otherwise reflects the way the processor works, it has distinct instructions for these operations, IMUL vs FMUL and IDIV vs FDIV. The latter one being rather famous for a bug in the Pentium processor :)

这篇关于在C#中使用System.Math.Pow()方法查找数字的立方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆