★ 基本

変数には四則演算が使えます。

C#の記号 数学の記号 機能
+ + 加算(足し算)
- - 減算(引き算)
* x 乗算(掛け算)
/ ÷ 除算(割り算)
% 剰余算(割り算の余り)
int score = 100;
Console.WriteLine(score); // 100

// 足し算
score = score + 300;
Console.WriteLine(score); // 400

// 引き算
score = score - 150;
Console.WriteLine(score); // 250

// 掛け算
score = score * 3;
Console.WriteLine(score); // 750

// 割り算
score = score / 5;
Console.WriteLine(score); // 150

たとえば足し算の場合は、score変数に「scoreに100を足したもの」を入れることで数を増やしています。

「%」を使えば数を割った際の余りも取得できます。

int score = 150;
Console.WriteLine(score % 60); // 30

また、四則演算にはショートカットがあります。

int score = 100;

// 足し算のショートカット
score += 100;

// 引き算のショートカット
score -= 150;

// 掛け算のショートカット
score *= 3;

// 割り算のショートカット
score /= 5;

// 数をひとつだけ足すショートカット
score++;

// 数をひとつだけ引くショートカット
score--;

★ 実践

スーパーマリオブラザーズのような、時間に応じてスコアが高くなる計算式です。

int score = 0;
int clearScore = 10000;
int time = 150;
int timeScore = 100;

// スコア = クリアスコア + (時間 * 100);
score = clearScore + timeScore * time;

Console.WriteLine(score);

ダメージ計算式の一つである「アルテリオス計算式」です。 攻撃力 - 防御力がダメージとなるシンプルな計算式となります。

int attack = 15;
int defence = 5;

int damage = attack - defense;
Console.WriteLine(damage + "ダメージ!");

消費税の計算です。

int riceball = 100;
int tea = 125;
float tax = 1.10f;

Console.WriteLine(riceball * tax);
Console.WriteLine(tea * tax);