loop.cs

Seungbin Yang / 양승빈·2024년 4월 2일

비주얼프로그래밍

목록 보기
10/21

코드

using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;

namespace _015_loop
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // (1) x에서 y까지의 합, 홀수의 합, 역수의 합

            Console.WriteLine("1. 다양한 합들");
            Console.Write("x를 입력하세요 : ");
            int x1 = int.Parse(Console.ReadLine());
            Console.Write("y를 입력하세요 : ");
            int y1 = int.Parse(Console.ReadLine());

            int max = 0;
            int min = 0;

            if (x1 > y1) { max = x1; min = y1; }
            else if (y1 > x1) { max = y1; min = x1; }

            int sum1 = 0;

            for (int i = min; i <= max; i++){
                sum1 += i;
            }
            Console.Write("합 : {0}\n", sum1);

            int odd = 0;
            for (int i = min; i <= max; i++){
                if (i % 2 == 1){
                    odd += i;
                }
            }
            Console.Write("홀수의 합 : {0}\n", odd);

            double rec = 0;

            for(int i = min; i <= max; i++){
                rec += 1.0 / i;
            }
            Console.Write("역수의 합 : {0}\n\n", rec);

            // (2) 구구단

            Console.WriteLine("2. 구구단");
            for (int i = 1; i <= 9; i++){
                for (int j = 1; j <= 9; j++) {
                    Console.Write("{0}*{1}={2}\t", i, j, i*j);
                }
                Console.Write("\n");
            }
            Console.Write("\n");

            // (3) x의 y승

            Console.WriteLine("3. 제곱");
            Console.Write("밑수를 입력하세요 : ");
            int x2 = int.Parse(Console.ReadLine());
            Console.Write("지수를 입력하세요 : ");
            int y2 = int.Parse(Console.ReadLine());

            int ex = 1;
            for (int i = 0; i < y2; i++) {
                ex = ex * x2;
            }
            Console.Write("{0}^{1}={2}\n\n", x2, y2, ex);

            // (4) n!

            Console.WriteLine("4. 팩토리얼");
            Console.Write("n을 입력하시오 : ");
            int n = int.Parse(Console.ReadLine());

            int fact = 1;
            for (int i = 1; i <= n; i++){
                fact = fact * i;
            }
            Console.Write("n! = {0}\n", fact);
        }
    }
}

출력 결과

Console.Write("x를 입력하세요 : "); 형태로
x 값을 입력받을 수 있다.
\t로 탭 기능을 사용할 수 있다.

0개의 댓글