대입 단축
Coddy Dart 여정의 기초 섹션에 포함된 레슨 — 94개 중 20번째.
Dart에서 복합 대입 연산자는 산술 연산자와 대입을 결합하여 변수를 간결하게 수정합니다.
1. 덧셈 대입 (+=)
void main() {
int score = 10;
score += 5; // 다음과 동일: score = score + 5;
print('Score after adding 5: $score');
}2. 뺄셈 대입 (-=)
void main() {
int lives = 3;
lives -= 1; // lives = lives - 1; 과 동일:
print('Lives after losing 1: $lives');
}3. 곱셈 대입 (*=)
void main() {
int points = 5;
points *= 2; // 다음과 동일: points = points * 2;
print('Points after doubling: $points');
}4. 나누기 대입 (/=)
void main() {
double price = 100.0;
price /= 2; // Equivalent to: price = price / 2;
print('Price after 50% discount: $price');
}챌린지
쉬움복합 대입 연산자를 사용하여 플레이어의 게임 통계를 추적하는 프로그램을 작성하세요:
- 초기값 100인 정수 변수
score를 선언하세요 - 초기값 50인 정수 변수
bonus를 선언하세요 - 초기값 2인 정수 변수
multiplier를 선언하세요 - 초기값 30인 정수 변수
penalty를 선언하세요 - 다음 메시지와 함께 초기 점수를 출력하세요:
Initial score: 100 +=연산자를 사용하여 보너스를 점수에 더하세요- 보너스를 더한 후 점수를 출력하세요:
Score after bonus: 150 *=연산자를 사용하여 점수를 승수로 곱하세요- 승수를 적용한 후 점수를 출력하세요:
Score after multiplier: 300 -=연산자를 사용하여 패널티를 점수에서 빼세요- 최종 점수를 출력하세요:
Final score: 270
출력은 위에 표시된 정확한 형식과 일치해야 합니다.
치트 시트
대입 단축 연산자는 산술 연산자와 대입을 결합하여 변수를 간결하게 수정합니다:
덧셈 대입 (+=)
score += 5; // Equivalent to: score = score + 5;뺄셈 대입 (-=)
lives -= 1; // Equivalent to: lives = lives - 1;곱셈 대입 (*=)
points *= 2; // Equivalent to: points = points * 2;나눗셈 대입 (/=)
price /= 2; // Equivalent to: price = price / 2;직접 해보기
void main() {
// 여기에 변수를 선언하세요
int score = ?;
int bonus = ?;
int multiplier = ?;
int penalty = ?;
// 초기 점수 출력
print("Initial score: $score");
// += 연산자를 사용하여 보너스 추가
score ? bonus;
// 보너스 후 점수 출력
print("Score after bonus: $score");
// *= 연산자를 사용하여 배율 적용
score ? multiplier;
// 배율 후 점수 출력
print("Score after multiplier: $score");
// -= 연산자를 사용하여 패널티 차감
score ? penalty;
// 최종 점수 출력
print("Final score: $score");
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.