在C#中,測試四舍五入的準確性通常涉及創建一個測試函數,該函數接受兩個輸入值(通常是浮點數),應用四舍五入規則,然后檢查結果是否符合預期。以下是一個簡單的示例,展示了如何編寫這樣的測試函數:
using System;
class RoundingTests
{
static void Main()
{
// 測試正數四舍五入
Assert.AreEqual(3, Round(2.6), "2.6 should round to 3");
Assert.AreEqual(4, Round(2.6, 0), "2.6 should round to 3 with 0 decimal places");
Assert.AreEqual(4, Round(2.6, 1), "2.6 should round to 3 with 1 decimal place");
Assert.AreEqual(4, Round(2.6, 2), "2.6 should round to 3 with 2 decimal places");
// 測試負數四舍五入
Assert.AreEqual(-3, Round(-2.6), "-2.6 should round to -3");
Assert.AreEqual(-4, Round(-2.6, 0), "-2.6 should round to -3 with 0 decimal places");
Assert.AreEqual(-4, Round(-2.6, 1), "-2.6 should round to -3 with 1 decimal place");
Assert.AreEqual(-4, Round(-2.6, 2), "-2.6 should round to -3 with 2 decimal places");
// 測試邊界情況
Assert.AreEqual(0, Round(0.5), "0.5 should round to 0");
Assert.AreEqual(0, Round(-0.5), "-0.5 should round to 0");
Assert.AreEqual(1, Round(0.5, 0), "0.5 should round to 1 with 0 decimal places");
Assert.AreEqual(1, Round(-0.5, 0), "-0.5 should round to 1 with 0 decimal places");
Console.WriteLine("All tests passed!");
}
// 自定義的四舍五入函數
static double Round(double value, int decimalPlaces = 2)
{
double factor = Math.Pow(10, decimalPlaces);
return Math.Round(value * factor) / factor;
}
}
在這個例子中,Round
函數接受一個 double
類型的數值和一個可選的 decimalPlaces
參數,用于指定要保留的小數位數。默認情況下,它會四舍五入到最接近的整數。Assert.AreEqual
方法用于比較函數的輸出和預期的結果。如果它們不相等,測試將失敗,并顯示提供的錯誤消息。
請注意,這個例子使用了 Math.Round
方法,它是C#中內置的四舍五入函數。如果你想要實現自己的四舍五入邏輯,你可以根據需要修改 Round
函數。在編寫測試時,確保覆蓋各種可能的輸入情況,包括正數、負數、零和邊界值。