并行数组用于查找最高元素

huangapple go评论77阅读模式
英文:

Parallel arrays for finding the highest element

问题

我想在“prices”数组中找到最高的元素,然后打印出“letters”数组中相应的元素。

关于我可以做什么,我需要一些建议。我尝试过输出letters[index],但由于作用域的原因,我遇到了错误。我对编程非常新,所以这真的让我困扰。

String[] letters = {"A", "B", "C", "D", "E", "F", "G"};
double[] prices = {1.00, 2.00, 50.00, 4.00, 5.00, 6.00, 7.00};
double big = prices[0];
// 使用循环查找数组中的最大值
for (int index = 0; index < prices.length; index++) {
    if (prices[index] > big) {
        big = prices[index];
    }
}
System.out.println("具有最高价值的字母是 " + letters[index]);
英文:

I want to find the highest element in the "prices" array then print the corresponding element in the "letters" array

I need some suggestions about what I can do. I have tried outputting letters[index] but I get an error because of the scope I think. I'm very new to coding so this is really stumping me right now.

  String[] letters = {&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;};
  double[] prices = {1.00, 2.00, 50.00, 4.00, 5.00, 6.00, 7.00};
  double big = prices[0];      
  //for loop to find the highest value in the array
   for(int index = 0; index &lt; prices.length; index++)  
   { 
    if(prices[index] &gt; big)
     {
        big = prices[index];     
     }             
   }       
 System.out.println(&quot;The letter with the highest value is &quot; + big);

答案1

得分: 1

你需要两个变量:一个用来跟踪当前的“最高值”,另一个用来跟踪此值的索引。

double big = prices[0];
int bigIndex = 0;

然后

if (prices[index] > big) {
    big = prices[index];
    bigIndex = index;
}

最后:

System.out.println("具有最高值的字母是:" + letters[bigIndex]);
英文:

You need two variables: one to keep track of the current "highest values" and one to keep track of the index of this value.

double big = prices[0];
int bigIndex = 0;

then

if (prices[index] &gt; big) {
    big = prices[index];
    bigIndex = index;
}

and finally:

System.out.println(&quot;The letter with the highest value is &quot; + letters[bigIndex]);

huangapple
  • 本文由 发表于 2020年10月25日 05:48:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64518311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定