【问题标题】:Why am I getting the wrong results from my algorithm implementations?为什么我从算法实现中得到错误的结果?
【发布时间】:2016-04-01 18:37:29
【问题描述】:

我有一个任务要通过以下算法(伪代码)创建 Java 代码方法:

Design Algorithm CalcLowest 
var lowest = first value in the array numList 
For index=1 to count-1 
If value at index is less than lowest 
Set lowest to value at index 
End if
End loop 

Design Algorithm CalcHighest 
var highest = first value in the array numList 
For index=1 to count-1 
If value at index is greater than highest 
Set highest to value at index 
End if 
End loop

我写了以下内容:

public int getHighest()
    {   
        int highest = marks[0];

        for (int i=0; i < count +1; i++){

            if(i > highest)

                highest = i;}

        return highest;

        }

 public int getLowest()
    {
           int lowest = marks[0];

           for (int i=0; i < count +1; i++){


               if(i < lowest)

                   lowest = i;}

           return lowest;

           }

    } 

它运行了,但最高值始终为 5,最低值始终为 0。为什么?

【问题讨论】:

  • 您将i 与最低值进行比较,您应该将marks[i] 与最低值进行比较
  • 谢谢你现在知道了 :-)

标签: java arrays algorithm


【解决方案1】:

您正在将 i 与最低值进行比较

if(i < lowest)

每次循环时,我都会递增。所以最低和最高将始终与您循环的次数相同。

不与 i 进行比较,而是与数组中第 i 位处的值进行比较。

【讨论】:

  • 如果是这样,请选择它作为您问题的答案:)
猜你喜欢
  • 2021-12-22
  • 2023-03-03
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多