프로그래밍/C#

C#에서 숫자 관련 기본 연산 수행

김꿀꿀이 2023. 3. 27. 11:25
반응형

오늘 학습 차례는 아래 링크 참고

http://learn.microsoft.com/ko-kr/training/modules/csharp-basic-operations/?ns-enrollment-type=learningpath&ns-enrollment-id=learn.wwl.get-started-c-sharp-part-1 

 

C#에서 숫자 관련 기본 연산 수행 - Training

숫자 데이터에 대해 기본 수학 연산을 수행하는 데 사용되는 연산자와 기술을 알아봅니다.

learn.microsoft.com

 

C#을 사용하여 첫 번째 코드 작성(C#로 시작, 파트 1)

- C#에서 숫자 관련 기본 연산 수행 -

 

* 변수끼리 더할 수 있다.
 - 숫자 변수끼리  더하면 숫자가 됨
 - 숫자 + 문자열 = 문자열로 인식됨

code>
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + widgetsSold + 7 + " widgets.");
output>
Bob sold 77 widgets.
>> widgetsSold + 7 은 14가 맞지만 문자열과 더해져 다 함께 문자열로 인식

code> 
string firstName = "Bob";
int widgetsSold = 7;
Console.WriteLine(firstName + " sold " + (widgetsSold + 7) + " widgets.");
output>
Bob sold 14 widgets.
>> 괄호를 이용하여 ( widgetsSold + 7 )로 감싸면 int끼리 먼저 연산 후 string과 더해지므로 14로 출력됨.


* 숫자 변수끼리 사칙연산 사용가능 ( +, -, *, / )
* a % b :  a를 b로 나눴을 때 나머지 값 계산
* 기본 연산 순서는 사칙연산의 우선순위 적용 ( *, / 가 +,- 보다 우선)
* 괄호를 이용하여 연산 순서를 원하는 대로 변경 가능
* 변수값의 리터럴값을 임시로 변경가능함

code>
int first = 7;
int second = 5;
decimal quotient = (decimal)first / (decimal)second;
Console.WriteLine(quotient);

output>
1.4

>> int로 선언된 first/second의 값은 1이지만 decimal로 변환해서 연산해서 소수점까지 출력됨.

* +, - 의 3가지 연산코드

int value = 1; 

value = value + 1;
value += 1;
value++;
>> 위의 세줄 모두 value의 값은 2가 된다.

value = value - 1;
value -= 1;
value--;
>> 위의 세줄 모두 value의 값은 0이 된다.


* ++ / -- 는 변수 앞에 위치하면 계산하고 출력 / 변수 뒤에 위치하면 출력하고 계산.

code >
int value = 1;
value++; // 1+1 연산

Console.WriteLine("First: " + value);
// 2
Console.WriteLine("Second: " + value++);
// 뒤에 계산되어 2 출력 후 2+1 되어 WriteLine 메서드 호출 이후 3이 됨.
Console.WriteLine("Third: " + value);
// 3
Console.WriteLine("Fourth: " + (++value));
// 앞에 계산되어 3+1 = 4 출력

output>
First: 2
Second: 2
Third: 3
Fourth: 4

 

* 예제

 - 화씨를 섭씨로 바꿔서 출력하는 예제로 3번의 연산방법을 이용하면 된다.

 

* 작성 코드

int fahrenheit = 94;
decimal celsius = ((decimal)fahrenheit-32)*(5m/9m);

Console.Write($"The temperature is {celsius} Celsius.");

 

* 예제 코드

int fahrenheit = 94;
decimal celsius = (fahrenheit - 32m) * (5m /9m);

Console.WriteLine("The temperature is "+ celsius +" Celsius.");

 

내가 작성한 코드보다 예제가 더 짧다.
출력 결과는 같지만 아무래도 코드는 간결하고 깔끔한 것이 좋으므로
나는 오늘도 마이크로소프트에 패배했다...

내일도 열심히 해봐야지!

반응형