【问题标题】:Proper syntax for changing the value of an array in a 'for' loop [closed]在“for”循环中更改数组值的正确语法[关闭]
【发布时间】:2017-12-22 18:13:30
【问题描述】:

好的,我只需要确保我的编码正确。有时间请查看以下内容:

int [] Counter_Event = new int [46];
for (int xCount = 0; xCount < Counter_Event.Length; xCount++)
    { Counter_Event[xCount] = Math.Round(xCount * 10000);}

使用上述内容,它会抛出一个编译错误。我可能没有使用正确的语法,但任何观点都会有所帮助。

【问题讨论】:

  • 编译错误消息可能包含一些关于您的语法不正确的信息。
  • 如果您包含编译错误会有所帮助。我在运行您的代码时遇到的错误是 Math.Round,CS0121 The call is ambiguous between the following methods or properties: 'Math.Round(double)' and 'Math.Round(decimal)'
  • 如果xCount 是一个int 而10000 是一个int,为什么需要Math.Round?它们已经是整数了……
  • 语法错误 - 这不是 booksMSDN 的用途吗?
  • @Plutonix 确实如此。甚至语法错误的工具提示也准确地解释了问题所在。

标签: c# arrays loops for-loop


【解决方案1】:

Math.Round() 需要 demicaldouble 作为参数。

这样的事情会起作用:

int[] Counter_Event = new int[46];
for (int xCount = 0; xCount < Counter_Event.Length; xCount++)
{ Counter_Event[xCount] = (int)Math.Round((double)xCount * 10000); }

【讨论】:

  • 是的,我的问题是假设 Math.Round 为 int 工作。根据此处的其他帖子,它适用于双精度和十进制。我的错。不过,我很欣赏上面的转换脚本。如果我以后需要走那条路,我会参考它。感谢 GBlock。
【解决方案2】:

您需要将Math.Round() 的参数类型转换为DoubleDecimal。此外,由于您的数组Counter_Event 的类型为int,因此您必须再次将Math.Round() 的结果转换为int,因为Math.Round() 返回类型是DecimalDouble

int [] Counter_Event = new int [46];
for (int xCount = 0; xCount < Counter_Event.Length; xCount++)
{ 
     Counter_Event[xCount] = (int)Math.Round((double)(xCount * 10000));
}

【讨论】:

  • 是的,这对我来说是一个愚蠢的举动。我完全按 Math.Round 分隔类型要求。感谢您抽出宝贵时间发帖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2016-10-29
  • 1970-01-01
  • 2021-09-25
  • 2020-09-17
  • 1970-01-01
相关资源
最近更新 更多