햄발
연산자 (산술)(증감 , 감소) 본문
산술 연산자
package basic.ch03;
public class Operation2 {
public static void main(String[] args) {
int result1 = 5 + 3;
int result2 = 5 - 3;
int result3 = 5 * 3;
// 고민해 볼 사항
// int result4 = 5 / 3;
double result4 = 5.0 / 3;
int result5 = 5 % 3;
System.out.println("result1 " + result1);
System.out.println("result2 " + result2);
System.out.println("result3 " + result3);
System.out.println("result4 " + result4);
System.out.println("result5 " + result5);
// 문제
// 1. (12 + 3) / 3 값을 화면에 출력해 보세요
// 변수명, 데이터 유형 스스로 결정하고 식을 만들어 보세요
// 2. (25 % 2) 값을 화면에 출력해 보세요
// 어떤 수를 2로 나누었을 때 나머지가 0이면 짝수 1이면 홀수
// 3. 15를 4로 나눈 후, 그 결과의 절대값을 출력하세요
// 도전 문제
// 직접 산술 연산자 문제 만들기 - (2문제 생성)
} // end of main
} // end of class
- 단항 연산자
- 변수의 값을 오직 1 더하거나 1 뺄때 사용
- 연산자가 항의 앞에 있는가 뒤에 있는가에 따라 연산 시점과 결과가 달라짐
- 문장(statement)의 끝(;)을 기준으로 연산 시점을 생각해야 함
package basic.ch03;
/**
* 증감,감소 연산자
* 변수에 접근해서 그 값을 조직 1증가 또는 1감소 시킨다.
*/
public class Operation3 {
public static void main(String[] args) {
int value1 = 1;
//value++1;
++value1;
System.out.println(value1);
// 변수에 접근해서 1 감소 시키기
int value2 = 1;
value2--;
System.out.println(value2);
// 증감 연산자가 변수 뒤에 올 때 (후의 연산자)
int intData1 = 10;
int resultData;
// 후의 연산자 연산자는 ; (세미콜론 기준으로 동작 합니다)
// 11 = <--- 10 + 1
resultData = intData1++;
System.out.println(resultData); // 결과 10
System.out.println(intData1);
// ; 세미콜론 기준으로 끝나고 변수에 접근해서 1을 증가 시켰다.
// ---> 여러분들을 전위 연산자로 사용하자
// 증감 연산자가 변수 앞에 올 경우(전위 연산자)
int intData2 = 100;
int resultData2;
resultData2 = ++intData2;
System.out.println(resultData2);
// 결론 : 증감 연산자는 변수의 값을 오직 1 증가 시킬때 사용 한다.
// 항에 앞,뒤 위치에 따라서 연산에 순서가 다르다.
} // end of main
} // end of class
'Java' 카테고리의 다른 글
연산자(관계, 논리, 빠른평가, 삼항) (2) | 2024.04.12 |
---|---|
연산자(복합 대입 연산자) (0) | 2024.04.12 |
연산자(항, 대입, 부호) (0) | 2024.04.11 |
명령어를 통한 컴파일, 실행 (0) | 2024.04.11 |
형 변환(type casting) (0) | 2024.04.11 |