'2020/03/25'에 해당되는 글 1건

  1. 2020.03.25 C# 의 세제곱근 구하는 함수 Cbrt()

 

C 언어나 C++ 언어에는 세제곱근을 구하는 함수 cbrt() 가 기본적으로 제공되어 있다.

소스에서 단지 #include <math.h> 또는 #include <cmath> 를 추가하기만 된다.

그러나 C# 언어에는 이런 함수가 기본적으로 제공되지 있지 않다. (Framework 의 경우)

그런데 Core 3.0 이상의 경우에는 C# 언어에서도 제곱근 함수 Sqrt() 와 세제곱근 함수 Cbrt() 를

기본적으로 사용할 수 있다. 

using System.Math;  구문이 없더라도 쓸 수 있다.

 

Visual Studion 2019에서 "새 프로젝트 만들기" -> "콘솔 앱(.NET Core)" 하고

프로젝트 이름을 적당히 써 주고 C# 소스 Progam.cs 를 편집하는 창에서

Main() 함수 부분을 다음과 같이 수정하고 빌드하여 실행한다.

 

static void Main(string[] args)
{
    // Calculate the cubic root of a single preceson type.
    float x = 27f;
    float y = MathF.Cbrt(x);
    Console.WriteLine("Cube root of {0} is {1}", x, y);
    
    // Calculate the cubic root of a double preceson type.
    double x2 = 0.000000000000125;
    double y2 = Math.Cbrt(x2);
    Console.WriteLine("Cube root of {0:F15} is {1:F5}", x2, y2);
    
    Console.Write("Press any key... ");
    Console.ReadLine();
}

 

그러면 컨솔 창에 실행 결과가 다음 처럼 출력된다.

Cube root of 27 is 3
Cube root of 0.000000000000125 is 0.00005
Press any key...

 

 

 

Posted by Scripter
,