代入のショートカット
CoddyのDartジャーニー「基礎」セクションの一部 — レッスン 20/94。
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; // 等価: score = score + 5;減算代入 (-=)
lives -= 1; // 等価: lives = lives - 1;乗算代入 (*=)
points *= 2; // 等価: points = points * 2;除算代入 (/=)
price /= 2; // 等価: 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");
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。