如何在 C# 中返回包含十进制数字的双精度数组?
这是我的第一个问题,所以我希望我能正确解释这一点;-)
我需要创建一个方法,该方法接受双精度数组、数字,并返回一个包含数字中每个元素的平方的新数组。 (任何帮助和指导将不胜感激。谢谢!)
我得到的参数如下:
<param name="numbers">Input array</param>
<returns>double array</returns>
public double[] PowerArray(double[] numbers)
这是我到目前为止所写的,但它返回双数。我需要返回包含十进制数字。
{
double[] PowerArray = Array.ConvertAll(numbers, i => i * i);
return PowerArray;
}
我的指示是按照以下示例返回我的答案: double[] input = { -2.2, 0, 1.1, 3 } 应该返回 double[] [4.84, 0, 1.21。 9]。我的回报给了我 double[] [4.840000000000001, 0, 1.2100000000000002, 9]。
This is my first question, so I hope I explain this correctly ;-)
I need to create a method that takes in a double array, numbers, and returns a new array containing the square of each element in numbers. (Any help and guidance will be greatly appreciated. Thank you!)
The parameters I have been given are as follows:
<param name="numbers">Input array</param>
<returns>double array</returns>
public double[] PowerArray(double[] numbers)
This is what I've written so far, but it returns double numbers. I need the return to contain decimal numbers.
{
double[] PowerArray = Array.ConvertAll(numbers, i => i * i);
return PowerArray;
}
My instructions are to return my answers following this example: double[] input = { -2.2, 0, 1.1, 3 } should return double[] [4.84, 0, 1.21. 9]. My return is giving me double[] [4.840000000000001, 0, 1.2100000000000002, 9].
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在了解浮点数学的基本性质。浮点数是近似值。您不需要近似值,因此不适合使用此数据类型。
相反,请使用
十进制
来执行数学运算。如果您确实需要的话,您可以将结果强制转换回double
。You're hitting the fundamental nature of floating point math. Floating point numbers are approximations. You don't want an approximation, therefore it's inappropriate to use this data type.
Instead, use
decimal
to perform the math. You can then cast the result back to adouble
if you really need it to be.