在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
函数。在编写测试时,确保覆盖各种可能的输入情况,包括正数、负数、零和边界值。