数学演算を特定の数値型として出力する課題の解決策を確認する

完了

次のコードは、前のユニットの課題に対して考えられる解答の 1 つです。

int value1 = 12;
decimal value2 = 6.2m;
float value3 = 4.3f;

// The Convert class is best for converting the fractional decimal numbers into whole integer numbers
// Convert.ToInt32() rounds up the way you would expect.
int result1 = Convert.ToInt32(value1 / value2);
Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");

decimal result2 = value2 / (decimal)value3;
Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");

float result3 = value3 / value1;
Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");

この課題には複数の回答が考えられるため、このコードは "考えられる解決策の 1 つ" にすぎません。 この解決策では、キャスト (および変換に向けた呼び出し) を多用しています。ただし、他のアプローチも同様に効力があります。 結果が次の出力と同じになることを確認してください。

Divide value1 by value2, display the result as an int: 2
Divide value2 by value3, display the result as a decimal: 1.4418604651162790697674418605
Divide value3 by value1, display the result as a float: 0.35833335

正しくできたなら、おめでとうございます。 次のユニットの知識チェックに進んでください。

重要

この課題を完了できなかった場合は、先に進む前に、これまでのユニットを確認した方がよいと思われます。