.NET프로그래밍/C# 3.5 SP1

22. 제곱 구하는 함수 프로그램

holland14 2009. 8. 5. 19:10


using System;

public class 제곱
{
    public static void Main()
    {

        // 2의 10승 : 1024
        // 2의 20승 : 1048576
        // 3의 3승 : 3 * 3 * 3 =27
        Console.WriteLine(Math.Pow(2, 20)); // 1048576
       
        // 아래 함수를 만들자.
        Console.WriteLine(MyPow(2, 10)); // 1024
        Console.WriteLine(MyPow(3, 3)); // 27
        Console.WriteLine(MyPow(2, 20)); // 1048576
    }
    // MyPow 함수를 설계해 보시오... 시행착오법을 거치세요...
    public static int MyPow(int a, int b)
    {
        int result = 1; // 1로 초기화
        for (int i = 0; i < b; i++)
        {
            result *= a; // 1 * a * a * ...
        }
        return result;
    }

}