대입 단축
Coddy Dart 여정의 기초 섹션에 포함된 레슨. 94개 중 20번째.
Dart에서 **할당 축약 연산자**(assignment shortcuts)는 산술 연산자와 할당을 결합하여 변수를 간결하게 수정합니다.
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; // 다음과 같음: price = price / 2;
print('Price after 50% discount: $price');
}챌린지
쉬움할당 축약 연산자를 사용하여 플레이어의 게임 통계를 추적하는 프로그램을 작성하세요:
- 초기값이 100인
int변수score를 선언하세요 - 초기값이 50인
int변수bonus를 선언하세요 - 초기값이 2인
int변수multiplier를 선언하세요 - 초기값이 30인
int변수penalty를 선언하세요 - 다음 메시지와 함께 초기
score를 출력하세요:Initial score: 100 +=연산자를 사용하여score에bonus를 더하세요bonus를 더한 후의score를 출력하세요:Score after bonus: 150*=연산자를 사용하여score에multiplier를 곱하세요multiplier를 적용한 후의score를 출력하세요:Score after multiplier: 300-=연산자를 사용하여score에서penalty를 빼세요- 최종
score를 출력하세요:Final score: 270
출력 결과는 위에 표시된 형식을 정확히 따라야 합니다.
직접 해보기
void main() {
// 여기에 변수를 선언하세요
// 아래의 플레이스홀더 값을 작업에서 주어진 값으로 바꾸세요
int score = 0;
int bonus = 0;
int multiplier = 0;
int penalty = 0;
// Print initial score
print("Initial score: $score");
// += 연산자를 사용하여 보너스를 더하세요
score = bonus;
// Print score after bonus
print("Score after bonus: $score");
// *= 연산자를 사용하여 배수를 적용하세요
score = multiplier;
// Print score after multiplier
print("Score after multiplier: $score");
// -= 연산자를 사용하여 페널티를 빼세요
score = penalty;
// 최종 점수를 출력하세요
print("Final score: $score");
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러