檢閱將數學運算輸出為特定數字類型挑戰的解決方案

已完成

下列程式碼是先前單元中挑戰的其中一個可能解決方案。

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}");

這段程式碼只是「一個可能的解決方案」,因為有好幾種方法可以解決這項挑戰。 此解決方案使用許多轉換 (以及呼叫轉換);不過,其他方法也可能同樣可行。 只要確定您的結果符合下列輸出即可。

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

如果成功,恭喜您! 請繼續進行下一個單元中的知識檢定。

重要

如果您無法順利完成此挑戰,您應該在繼續之前先複習上一個單元中的內容。