檢閱輸出數學運算作為特定數位類型挑戰的解決方案
下列程式代碼是上一個單元中挑戰的可能解決方案。
int value1 = 11;
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.3909091
如果您成功,恭喜! 繼續進行下一個單元中的知識檢定。
重要
如果您無法完成這項挑戰,或許您應該先檢閱先前的單元,再繼續作。