【问题标题】:Indexing issues with arrays数组的索引问题
【发布时间】:2013-12-12 03:03:54
【问题描述】:

我的代码用 5 个不同的值填充了一个大小为 5 的数组(代码未显示)。然后它用相应的数字填充数组中的每个索引(底部函数)。然后它保存之前最大的索引(最初从 0 开始)。然后它在数组中搜索最大值,保存该值和找到它的索引。

但是,当我多次运行它时,它永远不会给我当前的索引值 0。它总是为 1。例如。我第一次运行它,之前最大的索引是 0,当前索引是 1(这是正确的)。然后当我再次运行它时,第一个值是最大的。之前最大的索引为 1(正确),但当前的索引值也为 1。(应该为 0)。

有人能找出我的代码有什么问题吗?

float highestTemperature(float temperaturearray[])
{
  int arraylength = 5; //knows how large the array is
  hottest = temperaturearray[0];
  previouslargestindex = currentlargestindex;
  Serial.print("previous largest index = ");
  Serial.println(previouslargestindex);

  for(int i = 0; i < arraylength; i++) //loops through the array 
  {
    if(temperaturearray[i] > hottest) 
    {
      hottest = temperaturearray[i]; 
     currentlargestindex = i;
    } //end if statement 
  } //end for loop
  Serial.print("current largest index = ");
  Serial.println(currentlargestindex);
}

float fillarray(float temperaturearray[])
{
  sensors.requestTemperatures();
  temperaturearray[0] = sensors.getTempC(Probe01);
  temperaturearray[1] = sensors.getTempC(Probe02);
  temperaturearray[2] = sensors.getTempC(Probe03);
  temperaturearray[3] = sensors.getTempC(Probe04);
  temperaturearray[4] = sensors.getTempC(Probe05);
}

【问题讨论】:

  • 尝试将 i++ 更改为 ++i 不确定
  • 这两个函数都说它们返回一个浮点数,但实际上它们什么都不返回。
  • println 是否实际打印float,还是它想要一个 C 风格的字符串?我怀疑是后者。此外,您需要在查找最大索引的循环之前将 currentlargestindex 初始化为 0,否则如果最大索引为 0,它将无法正确更新 currentlargestindex

标签: c++ arrays indexing arduino


【解决方案1】:

您应该将hottest 初始化为一个小于数组中任何温度的值。原因是,如果最热的温度在索引 0 中,那么当 i0 并且 currentlargestindex 不会更新时,if(temperaturearray[i] &gt; hottest) 将不会为真。

我建议使用FLT_MINstd::numeric_limits&lt;float&gt;::min(),但您知道的任何值都会更小。

您也可以尝试if(temperaturearray[i] &gt;= hottest),尽管浮点相等可能很复杂。如果按所示分配值就是您所做的一切,那应该没问题。

【讨论】:

  • 等号是我所缺少的。感谢您的帮助。
  • 不,你不是!正如答案所说,您未能初始化!
【解决方案2】:

你的失败是初始化currentlargestindex

正如你所做的hottest = temperaturearray[0]; 你也应该做currentlargestindex=0;

但是,您的代码可以得到更多改进:

float highestTemperature(float temperaturearray[]) {
  int arraylength = 5; //knows how large the array is
  int currentlargestindex = 0; //Assume first item is hottest one
  for(int i = 1; i < arraylength; i++) {//Don't need to check 0 again, check just 1, ...!
    if(temperaturearray[i] > temperaturearray[currentlargestindex]) {
      currentlargestindex = i; 
      //hottest=temperaturearray[i]; //Not needed, same as temperaturearray[currentlargestindex]
    }
  }
  //This is a float returning function, so return it!
  return temperaturearray[currentlargestindex];
}

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多