본문 바로가기
Program Language/C#

Part1. C# 첫발 내딛기(16. 산술 연산자)

by 토담이아빠 2023. 1. 9.

산술 연산자

 

이번 포스팅은 연산자 중에 기본이라고 할 수 있는 산술 연산자에 대해 정리했습니다.


산술 연산자

 

산술연산자는 4개의 사칙연산자(+, -, *, /)와 나머지(%) 연산자로 총 5가지가 있습니다. 산술연산은 피연산자의 자료형에 따라 계산 결과값의 자료형도 결정됩니다. 특히 주의해야 하는 것은 '정수 / 정수'의 결과는 정수라는 점입니다. 예를 들어 1/2의 결과는 0.5가 아니고 0이 됩니다. '정수 / 실수'의 결과는 실수입니다. C/C++과 달리 % 연산자는 실수형에도 사용할 수 있습니다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArithmeticOperators
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("정수의 계산");
            Console.WriteLine(123 + 45);
            Console.WriteLine(123 - 45);
            Console.WriteLine(123 * 45);
            Console.WriteLine(123 / 45);
            Console.WriteLine(123 % 45);

            Console.WriteLine("\n실수의 계산");
            Console.WriteLine(123.45 + 67.89);
            Console.WriteLine(123.45 - 67.89);
            Console.WriteLine(123.45 * 67.89);
            Console.WriteLine(123.45 / 67.89);
            Console.WriteLine(123.45 % 67.89);
        }
    }
}

사칙연산과 나머지 연산에 대해서 정수 연산과 실수 연산결과를 출력합니다.


결과


[Review]

"초보자를 위한 C# 200제(2판)"  저자 / 강병익

댓글