C#/Basic

C# 연산자 기초

hun.a 2025. 6. 29. 23:41
반응형

연산자 기초

연산자란 무엇인가?

연산자(Operator)는 데이터에 대해 특정한 작업을 수행하는 기호입니다. 수학에서 사용하는 +, -, ×, ÷와 비슷하다고 생각하면 됩니다.

int a = 10;
int b = 5;
int result = a + b;  // + 는 덧셈 연산자
Console.WriteLine(result);  // 15 출력

산술 연산자

숫자 계산에 사용하는 기본적인 연산자들입니다.

기본 산술 연산자

int x = 20;
int y = 6;

Console.WriteLine($"{x} + {y} = {x + y}");  // 덧셈: 26
Console.WriteLine($"{x} - {y} = {x - y}");  // 뺄셈: 14
Console.WriteLine($"{x} * {y} = {x * y}");  // 곱셈: 120
Console.WriteLine($"{x} / {y} = {x / y}");  // 나눗셈: 3 (정수 나눗셈)
Console.WriteLine($"{x} % {y} = {x % y}");  // 나머지: 2

주의할 점: 정수 나눗셈

정수끼리 나누면 소수점이 버려집니다!

int a = 7;
int b = 2;

int intResult = a / b;        // 3 (소수점 버림)
double doubleResult = (double)a / b;  // 3.5 (정확한 결과)

Console.WriteLine($"정수 나눗셈: {intResult}");
Console.WriteLine($"실수 나눗셈: {doubleResult}");

복합 대입 연산자

계산 결과를 같은 변수에 다시 저장할 때 사용합니다.

int score = 80;

score += 10;  // score = score + 10;과 같음
Console.WriteLine($"점수 증가: {score}");  // 90

score -= 5;   // score = score - 5;와 같음
Console.WriteLine($"점수 감소: {score}");  // 85

score *= 2;   // score = score * 2;와 같음
Console.WriteLine($"점수 두 배: {score}");  // 170

score /= 10;  // score = score / 10;와 같음
Console.WriteLine($"점수 나누기: {score}");  // 17

증감 연산자

값을 1씩 증가시키거나 감소시킬 때 사용합니다.

int counter = 5;

Console.WriteLine($"원래 값: {counter}");        // 5

// 후위 증가: 먼저 값을 사용하고 나서 1 증가
Console.WriteLine($"후위 증가: {counter++}");     // 5 출력 후 counter는 6이 됨
Console.WriteLine($"증가 후: {counter}");        // 6

// 전위 증가: 먼저 1 증가하고 나서 값을 사용
Console.WriteLine($"전위 증가: {++counter}");     // 7 출력 (먼저 증가)

// 감소 연산자도 마찬가지
Console.WriteLine($"후위 감소: {counter--}");     // 7 출력 후 counter는 6이 됨
Console.WriteLine($"전위 감소: {--counter}");     // 5 출력 (먼저 감소)

비교 연산자

두 값을 비교해서 참(true) 또는 거짓(false)을 반환합니다.

int age = 25;
int adultAge = 18;

Console.WriteLine($"{age} > {adultAge}: {age > adultAge}");    // true
Console.WriteLine($"{age} < {adultAge}: {age < adultAge}");    // false
Console.WriteLine($"{age} >= {adultAge}: {age >= adultAge}");  // true
Console.WriteLine($"{age} <= {adultAge}: {age <= adultAge}");  // false
Console.WriteLine($"{age} == {adultAge}: {age == adultAge}");  // false
Console.WriteLine($"{age} != {adultAge}: {age != adultAge}");  // true

주의: 등호 비교는 ==을 사용합니다. =는 대입 연산자입니다!

논리 연산자

불린(bool) 값들을 조합할 때 사용합니다.

bool isStudent = true;
bool hasID = true;
bool isAdult = false;

// AND 연산자 (&&): 모든 조건이 참일 때만 참
bool canEnterLibrary = isStudent && hasID;
Console.WriteLine($"도서관 입장 가능: {canEnterLibrary}");  // true

// OR 연산자 (||): 하나라도 참이면 참
bool canVote = isAdult || age >= 18;
Console.WriteLine($"투표 가능: {canVote}");  // true

// NOT 연산자 (!): 참을 거짓으로, 거짓을 참으로
bool isNotStudent = !isStudent;
Console.WriteLine($"학생이 아님: {isNotStudent}");  // false

복합 조건 예제

int temperature = 25;
bool isRaining = false;
bool hasUmbrella = true;

// 복합 조건: 날씨가 좋거나 (비가 오지만 우산이 있을 때) 외출 가능
bool canGoOut = (temperature > 20 && !isRaining) || (isRaining && hasUmbrella);
Console.WriteLine($"외출 가능: {canGoOut}");  // true

C# 9.0의 새로운 기능: 패턴 매칭

C# 9.0에서 도입된 not 패턴을 사용하면 더 간단하게 조건을 표현할 수 있습니다.

string? userName = Console.ReadLine();

// 기존 방식
if (userName != null)
{
    Console.WriteLine($"안녕하세요, {userName}님!");
}

// C# 9.0 not 패턴 (더 읽기 쉬움)
if (userName is not null)
{
    Console.WriteLine($"안녕하세요, {userName}님!");
}

연산자 우선순위

여러 연산자가 함께 사용될 때의 계산 순서를 알아야 합니다.

int result1 = 10 + 5 * 2;        // 20 (곱셈이 먼저)
int result2 = (10 + 5) * 2;      // 30 (괄호가 먼저)

bool condition = 5 > 3 && 10 < 20 || false;  // true

Console.WriteLine($"10 + 5 * 2 = {result1}");
Console.WriteLine($"(10 + 5) * 2 = {result2}");
Console.WriteLine($"복합 조건: {condition}");

우선순위 순서 (높은 것부터)

  1. 괄호 ()
  2. 증감 연산자 ++, --
  3. 곱셈, 나눗셈, 나머지 *, /, %
  4. 덧셈, 뺄셈 +, -
  5. 비교 연산자 <, >, <=, >=
  6. 등호 연산자 ==, !=
  7. 논리 AND &&
  8. 논리 OR ||
  9. 대입 연산자 =, +=, -=

실전 예제: 간단한 계산기

배운 연산자들을 활용해서 간단한 계산 프로그램을 만들어보겠습니다.

using System;

namespace SimpleCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("=== 간단한 계산기 ===");

            Console.Write("첫 번째 숫자를 입력하세요: ");
            double firstNumber = double.Parse(Console.ReadLine());

            Console.Write("두 번째 숫자를 입력하세요: ");
            double secondNumber = double.Parse(Console.ReadLine());

            // 계산 수행
            double sum = firstNumber + secondNumber;
            double difference = firstNumber - secondNumber;
            double product = firstNumber * secondNumber;
            double quotient = firstNumber / secondNumber;

            // 결과 출력
            Console.WriteLine("\n=== 계산 결과 ===");
            Console.WriteLine($"{firstNumber} + {secondNumber} = {sum}");
            Console.WriteLine($"{firstNumber} - {secondNumber} = {difference}");
            Console.WriteLine($"{firstNumber} × {secondNumber} = {product}");
            Console.WriteLine($"{firstNumber} ÷ {secondNumber} = {quotient:F2}");

            // 조건 판단
            bool isFirstLarger = firstNumber > secondNumber;
            bool areEqual = firstNumber == secondNumber;

            Console.WriteLine($"\n첫 번째 숫자가 더 큰가요? {isFirstLarger}");
            Console.WriteLine($"두 숫자가 같나요? {areEqual}");

            // C# 9.0 패턴 매칭 활용
            if (secondNumber is not 0)
            {
                Console.WriteLine("나눗셈 결과가 유효합니다.");
            }
            else
            {
                Console.WriteLine("0으로 나눌 수 없습니다!");
            }
        }
    }
}

실습 과제

다음 과제들을 직접 해보세요:

  1. 나이 계산기: 태어난 해를 입력받아 현재 나이를 계산하고, 성인인지 판단하는 프로그램을 만들어보세요.

  2. 점수 등급 계산기: 점수를 입력받아 A(90 이상), B(80 이상), C(70 이상), D(60 이상), F(60 미만) 등급을 판단하는 프로그램을 만들어보세요.

  3. 온도 변환기: 섭씨온도를 입력받아 화씨온도로 변환하고, 날씨 상태(추��, 적당함, 더움)를 판단하는 프로그램을 만들어보세요.

핵심 정리

  • 산술 연산자: +, -, *, /, % 및 복합 대입 연산자 (+=, -=, 등)
  • 비교 연산자: ==, !=, <, >, <=, >=
  • 논리 연산자: &&(AND), ||(OR), !(NOT)
  • 증감 연산자: ++, -- (전위/후위 구분)
  • C# 9.0 패턴: is not null 같은 패턴 매칭으로 더 읽기 쉬운 코드

다음 단계

연산자의 기초를 익혔습니다! 다음 글에서는 문자열을 다루는 다양한 방법들을 배워보겠습니다.

반응형