gpt4 book ai didi

c# - Assert.AreEqual for float without delta

转载 作者:行者123 更新时间:2023-11-30 22:29:56 25 4
gpt4 key购买 nike

我有一个用列表构建的深树结构,包含列表和 float 。我想对这样的结构进行断言,而不能对 float 使用增量。我的问题是,使用失败断言的输出是不够的,因为需要一到两位额外的小数。我必须猜测这些小数点才能继续。

using System.Collections;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestAssertLab
{
public class List : ArrayList {
public List(params object[] list) {
AddRange(list);
}
public override bool Equals(object other) {
List l = other as List;
if (l != null) {
if (Count != l.Count) return false;
return !l.Cast<object>().Where((t, i) => !this[i].Equals(t)).Any();
}
return false;
}
public override string ToString() {
string s = this.Cast<object>().Aggregate("", (current, item) => current + (item + ","));
return "[" + s.TrimEnd(',') + "]";
}
}

[TestClass]
public class AssertLab
{
public List z(params object[] l) {
return new List(l);
}
[TestMethod]
public void TestFails() {
List expected = z(0.1428571f, z(101, 102));
List actual = z(1/7.0f, z(101, 102));
Assert.AreEqual(expected, actual);
// output: Assert.AreEqual failed. Expected:<[0.1428571,[101,102]]>. Actual:<[0.1428571,[101,102]]>.
}
[TestMethod]
public void TestOK()
{
List expected = z(0.142857143f, z(30101, 30102));
List actual = z(1 / 7.0f, z(30101, 30102));
Assert.AreEqual(expected, actual);
}
}
}

最佳答案

您可以将它们转换为十进制:

(Decimal) 0.1428571f == (Decimal)(1 / 7.0f)

关于c# - Assert.AreEqual for float without delta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9950644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com