산술연산자는 4개의 사직연산자(+, -, *, /) 와 나머지(%) 연산자로 총 5가지가 있다.
연산의 결과는 숫자이다.
산술연산자에서 중요한것은 자료형이다. 즉, 피연산자의 자료형에 따라 계산 결과값의 자료형도 결정된다.
특히 주의해야 하는 것은
"정수/정수"의 결과는 정수라는 점이다.
예를 들어, 1/2의 결과는 0.5가 아니고 0이 된다.
"정수/실수"의 결과는 실수이다.
C나 c++과 달리 %연산자는 실수형에도 사용할 수 있다.
namespace _062_A017_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);
}
}
}
Console.WriteLine("정수의 계산");
- 콘솔에 "정수의 계산" 이라고 출력한다.
Console.WriteLine(123 + 45);
Console.WriteLine(123 - 45);
Console.WriteLine(123 * 45);
Console.WriteLine(123 / 45);
Console.WriteLine(123 % 45);
- 123 과 45를 +, -, *, /, % 연산자로 계산한 결과를 출력한다. / 연산자의 경우 정수와 정수의 연산이므로 출력도 정수인 2가 출력된다.
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);
- 123.45와 67.89를 +, -, *, /, % 연산자로 계산한 결괄르 출력한다.
** C , C++에서는 실수로 %연산이 불가능하다.
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
'코딩 책공부 > 초보자를 위한 C# 200제 2판' 카테고리의 다른 글
OverflowException과 checked키워드 (0) | 2024.04.17 |
---|---|
DivideByZeroException과 try~catch문 (0) | 2024.04.16 |
C#의 연산자와 식 (0) | 2024.04.11 |
Convert 클래스와 2진수, 8진수, 16진수 출력 (0) | 2024.04.04 |
문자열과 숫자의 변환 (0) | 2024.04.03 |