728x90
switch문
switch문은 아래와 같이 case에 맞는 값을 지정해 줄 수 있다.
int score = 95; string grade = "";
int score = (int)(Math.Truncate(input/10.0) * 10; //1의 자리를 버림
switch (score)
{
case 90:
grade = "A";
break;
case 80:
grade = "B";
break;
case 70:
grade = "C";
break;
case 60:
grade = "D";
break;
default:
grade = "F";
}
switch 식
switch문은 break;나 case: 등 반복되는 코드가 많은 것을 볼 수 있다. 이때, switch 식을 사용하면 코드의 길이를 줄이고 가독성을 높일 수 있다.
int score = 90;
string grade = (int)(Math.Truncate(score / 10.0) * 10) switch
{
90 => "A",
80 => "B",
70 => "C",
60 => "D",
_ => "F"
};
728x90
'🖥️ > C#' 카테고리의 다른 글
[C#] 참조 매개변수 전달, 여러 개의 값return, 가변 개수의 인수, 선택적 인수 (0) | 2023.08.16 |
---|---|
[이것이 C#이다] Chapter05: 연습문제 (0) | 2023.08.16 |
[이것이 C#이다] Chapter4 연습문제 (0) | 2023.08.16 |
[C#] null 조건부 연산자, 병합 연산자 (0) | 2023.08.16 |
[이것이 C#이다] Chapter3 연습문제 (0) | 2023.08.16 |