타입 캐스팅
Coddy C# 여정의 기초 섹션에 포함된 레슨 — 69개 중 14번째.
타입 캐스팅(Type casting)은 값을 한 데이터 타입에서 다른 데이터 타입으로 변환하는 과정입니다.
C#에서 정수를 double로, double을 정수로, 그리고 그 이상으로 변환할 수 있습니다. 캐스팅에는 두 가지 유형이 있습니다: 암시적(자동) 및 명시적(수동) 캐스팅입니다.
예를 들어 Integer to Double의 경우입니다:
암시적(자동) 형변환:
int number = 5;
double decimal_implicit = number; // 자동으로 5.0이 됩니다
// 계산과 함께
int x = 7;
double result_implicit = x / 2.0; // 결과는 3.5입니다명시적(수동) 캐스팅 Double to Integer:
double decimal_explicit = 9.7;
int number_explicit = (int) decimal_explicit; // 9가 됨 (소수점 이하는 버려짐)
// 계산과 함께
double price = 19.99;
int roundedPrice = (int) price; // 19가 됨챌린지
초급형 변환(type casting)을 보여주는 C# 프로그램을 작성하세요. 다음 작업을 수행하세요:
- 이름이
price인double변수를 선언하고99.99값으로 초기화하세요. price변수를int형으로 캐스팅하고 그 결과를 이름이intPrice인 새로운 변수에 저장하세요.price와intPrice의 값을 콘솔에 출력하세요.
치트 시트
형 변환(Type casting)은 값을 한 데이터 타입에서 다른 데이터 타입으로 변환하는 것을 말합니다. 여기에는 두 가지 유형이 있습니다:
암시적 형 변환 (자동) - 작은 타입에서 큰 타입으로 변환:
int number = 5;
double decimal_implicit = number; // 자동으로 5.0이 됩니다.명시적 형 변환 (수동) - 큰 타입에서 작은 타입으로 변환:
double decimal_explicit = 9.7;
int number_explicit = (int) decimal_explicit; // 9가 됩니다 (소수점 이하 절삭)직접 해보기
using System;
public class Program {
public static void Main(string[] args) {
// 변수 선언 및 초기화
double price = 99.99;
int intPrice = ?;
// 값 출력
Console.WriteLine("Price: " + price);
Console.WriteLine("Int Price: " + intPrice);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.