如何測(cè)試C#四舍五入的準(zhǔn)確性

c#
小樊
82
2024-10-16 06:13:04

在C#中,測(cè)試四舍五入的準(zhǔn)確性通常涉及創(chuàng)建一個(gè)測(cè)試函數(shù),該函數(shù)接受兩個(gè)輸入值(通常是浮點(diǎn)數(shù)),應(yīng)用四舍五入規(guī)則,然后檢查結(jié)果是否符合預(yù)期。以下是一個(gè)簡(jiǎn)單的示例,展示了如何編寫這樣的測(cè)試函數(shù):

using System;

class RoundingTests
{
    static void Main()
    {
        // 測(cè)試正數(shù)四舍五入
        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");

        // 測(cè)試負(fù)數(shù)四舍五入
        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");

        // 測(cè)試邊界情況
        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!");
    }

    // 自定義的四舍五入函數(shù)
    static double Round(double value, int decimalPlaces = 2)
    {
        double factor = Math.Pow(10, decimalPlaces);
        return Math.Round(value * factor) / factor;
    }
}

在這個(gè)例子中,Round 函數(shù)接受一個(gè) double 類型的數(shù)值和一個(gè)可選的 decimalPlaces 參數(shù),用于指定要保留的小數(shù)位數(shù)。默認(rèn)情況下,它會(huì)四舍五入到最接近的整數(shù)。Assert.AreEqual 方法用于比較函數(shù)的輸出和預(yù)期的結(jié)果。如果它們不相等,測(cè)試將失敗,并顯示提供的錯(cuò)誤消息。

請(qǐng)注意,這個(gè)例子使用了 Math.Round 方法,它是C#中內(nèi)置的四舍五入函數(shù)。如果你想要實(shí)現(xiàn)自己的四舍五入邏輯,你可以根據(jù)需要修改 Round 函數(shù)。在編寫測(cè)試時(shí),確保覆蓋各種可能的輸入情況,包括正數(shù)、負(fù)數(shù)、零和邊界值。

0