提问人:Quantum_Kernel 提问时间:12/12/2022 更新时间:12/12/2022 访问量:114
使用C降低数字数组精度的有效方法#
Efficient method for reducing the precision of an array of numbers using C#
问:
使用 C#,在不更改类型的情况下将浮点数数组的精度降低 n 位的有效方法是什么?
例:
float[]{1.34, 2.22, 2.32, 7.71}
成为
float[]{1.00, 2.00, 2.00, 8.00}
或
float[]{1.30, 2.20, 2.30, 7.70}
答:
5赞
theemee
12/12/2022
#1
var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};
for (int i = 0; i < array.Length; i++) {
array[i] = MathF.Round(array[i], 1); // the second argument is the number of digits after the dot
}
这将修改现有数组,结果将是float[]{1.30f, 2.20f, 2.30f, 7.70f}
如果要创建一个新数组:
var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};
var roundedArray = array.Select(x => MathF.Round(x, 1)).ToArray(); // or .ToList()
下一个:如何显示所有小数点?
评论
ForEach<T>
,