首页 > 解决方案 > 保存十进制值数组以使用 for 循环

问题描述

我想创建一个数组increment_Num[],如下所示:[1.60,1.62,1.64,1.66,1.68,1.70]

  //First step I converted the string to decimal value here:
  decimal Start_Num = decimal.Parse("1.60");
  decimal Stop_Num = decimal.Parse("1.70");
  decimal Steps_Num = decimal.Parse("0.02");
  
  //Second step I calculated the total number of points and converted the decimal value to int here:    
  decimal steps = (Stop_Num - Start_Num) /Steps_Num;
  int steps_int=(int)decimal.Ceiling(steps);
  
  //Third step I tried to create a for loop which will create an array       
  decimal[] increment_Num = new decimal[steps_int+1];
  for (decimal f=0; f<steps_int+1; f+=Steps_Num)
  {
  increment_Num[f] = Start_Num + f * Steps_Num;
  }

以下代码在倒数第二行的第 3 步给出了这个错误increment_Num[f]

错误 CS0266 无法将类型“十进制”隐式转换为“整数”。存在显式转换(您是否缺少演员表?)

我在声明中做错了吗?

标签: c#

解决方案


发表我的评论作为答案:

increment_Num[f]uf用作索引,数组由 int 索引,f 是小数

代码应该是

for (int index =0; index<=steps_int;  index++)
{   
    increment_Num[index] = Start_Num + index * Steps_Num;
}

推荐阅读