練習 - 完成將數學運算輸出為特定數字類型的挑戰

已完成

以下是使用您所學到的轉型和轉換內容來解決編碼挑戰的第二個機會。

下列挑戰可協助您了解將值轉型的含意,並考慮縮小轉換和放大轉換的影響。

  1. 將早先練習中的所有程式碼刪除或註解化。

  2. 輸入下列「起始」程式碼:

    int value1 = 12;
    decimal value2 = 6.2m;
    float value3 = 4.3f;
    
    // Your code here to set result1
    // Hint: You need to round the result to nearest integer (don't just truncate)
    Console.WriteLine($"Divide value1 by value2, display the result as an int: {result1}");
    
    // Your code here to set result2
    Console.WriteLine($"Divide value2 by value3, display the result as a decimal: {result2}");
    
    // Your code here to set result3
    Console.WriteLine($"Divide value3 by value1, display the result as a float: {result3}");
    
  3. 以您自己的程式碼取代起始程式碼中的程式碼註解,以解決挑戰:

    • 解決 result1value1 除以 value2,將結果顯示為 int
    • 解決 result2value2 除以 value3,將結果顯示為 decimal
    • 解決 result3value3 除以 value1,將結果顯示為 float

    解決挑戰,以便您的輸出類似:

    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
    
  4. 在 Visual Studio Code 的 [檔案] 功能表上,選取 [儲存]。

    在建置或執行程式碼之前,必須先儲存 Program.cs 檔案。

  5. 在 [總管] 面板中,若要在 TestProject 資料夾位置開啟 [終端],請以滑鼠右鍵按一下 [TestProject],然後選取 [在整合式終端機中開啟]。

    終端窗格應開啟,且應包含命令提示字元,顯示已對 TestProject 資料夾位置開啟終端。

  6. 在終端命令提示字元中,若要執行程式碼,請輸入 dotnet run,然後按 Enter 鍵。

    您應該會看見下列輸出:

    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
    

    注意

    如果您看到訊息指出「找不到要執行的專案」,請確定終端命令提示字元會顯示預期的 TestProject 資料夾位置。 例如:C:\Users\someuser\Desktop\csharpprojects\TestProject>

無論是遇到困難需要查看解決方案,還是已成功完成,都請繼續檢視此挑戰的解決方案。