Find Cube root of a number Using System.Math.Pow() method in C#

前端 未结 5 995
面向向阳花
面向向阳花 2020-12-18 05:10

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

when I used the below code, I was getting an incorrect value for the

相关标签:
5条回答
  • 2020-12-18 05:48
    public static void Main()
    {
        int a= int.Parse(Console.ReadLine());
        int sum=0;
    
        for(int i=0 ; i<= a ;i++)
        {
            for(int j=0 ; j<i ;j++)
            {
                sum =+ (i*i);
            }
            Console.WriteLine("Number is : {0} and cube of the {0} is :{1} \n",i,sum*i);
        }
    }
    
    0 讨论(0)
  • 2020-12-18 05:54

    The error (which, by the way, is just 4E-16 - 400 quintillionths) is caused by floating point errors.

    You could circumvent this by rounding the number if it is within a certain threshold:

    public static void cubicPairs(double n)
    {
        double root = (System.Math.Pow(n, (1/3)));
        double roundedRoot = Math.Round(root);
    
        if (Math.Abs(roundedRoot - root) < VERY_SMALL_NUMBER)
            return roundedRoot;
        else
            return root;
    }
    

    Where VERY_SMALL_NUMBER can be, say, 1e-10.

    0 讨论(0)
  • 2020-12-18 05:54

    Try it

    Math.Ceiling(Math.Pow(n, (double)1 / 3));
    
    0 讨论(0)
  • 2020-12-18 05:59

    You can try running this code for cube root functionality.

    textBox2.Text = Math.Pow(Convert.ToDouble(textBox1.Text), 0.3333333333333333).ToString();
    
    0 讨论(0)
  • 2020-12-18 06:09

    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

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

    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 :)

    0 讨论(0)
提交回复
热议问题