数组最小值查找方法失效,请求技术排查帮助
数组最小值查找方法异常问题
我正在进行数组相关练习(说明:这不是作业,刚考完试,感觉肯定没通过,所以在练习),在对数组执行操作时遇到问题。我实现的查找最大值、平均值及总和的方法均正常,但查找最小值的方法却无法正常工作,我实在搞不清楚原因。
数组结构说明
- 索引0用于存储最大值
- 索引1用于存储最小值
我的查找最小值/最大值的方法从索引2开始遍历,因为最小值/最大值会存储在数组的前两个元素中。数组大小及文件读取逻辑也考虑到了这一点,均从索引2开始处理。
我也尝试了返回值类型的方法,但得到的结果依然相同。
尝试过的无效方法
方法一:适配数组结构(从索引2遍历)
该方法计划将最大值赋值给salesArray[0],最小值赋值给salesArray[1],适配了数组大小及从索引2开始读取的逻辑:
private void Lowest() { //method variables double lowest = salesArray[1]; //find lowest sale for (int index = 2; index < salesArray.Length; index++) { if(salesArray[index] < lowest) { lowest = salesArray[index]; } } }
方法二:按建议从索引0开始遍历
尝试将最大值/最小值的查找起始位置改为索引0:
private void Lowest() { //method variables double lowest = salesArray[0]; //find lowest sale for (int index = 1; index < salesArray.Length; index++) { if(salesArray[index] < lowest) { lowest = salesArray[index]; } } }
方法三:返回值类型方法
尝试用返回值的方式实现查找:
private double Lowest(double[] salesArray) { //method variables double lowest = salesArray[0]; //find lowest sale for (int index = 1; index < salesArray.Length; index++) { if (salesArray[index] < lowest) { lowest = salesArray[index]; } } return lowest; }
程序输出截图

内容的提问来源于stack exchange,提问作者Ashley Brown
相关产品推荐
相关产品推荐

