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

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

Parallel arrays for finding the highest element

问题

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

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

  1. String[] letters = {"A", "B", "C", "D", "E", "F", "G"};
  2. double[] prices = {1.00, 2.00, 50.00, 4.00, 5.00, 6.00, 7.00};
  3. double big = prices[0];
  4. // 使用循环查找数组中的最大值
  5. for (int index = 0; index < prices.length; index++) {
  6. if (prices[index] > big) {
  7. big = prices[index];
  8. }
  9. }
  10. 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.

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

答案1

得分: 1

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

  1. double big = prices[0];
  2. int bigIndex = 0;

然后

  1. if (prices[index] > big) {
  2. big = prices[index];
  3. bigIndex = index;
  4. }

最后:

  1. 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.

  1. double big = prices[0];
  2. int bigIndex = 0;

then

  1. if (prices[index] &gt; big) {
  2. big = prices[index];
  3. bigIndex = index;
  4. }

and finally:

  1. 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:

确定