简体   繁体   English

如何用C查找数组中的3个最大偶数?

[英]How to find 3 largest even numbers in an array with C?

I need to find 3 largest numbers in an array and then add them together. 我需要在数组中找到3个最大的数字,然后将它们加在一起。

For example: Input: 3 4 7 10 11 16 16 23 26 Output: The sum of the 3 largest even numbers are: 16, 16, 26. The sum is 58 例如:输入:3 4 7 10 11 16 16 23 26输出:3个最大偶数之和为:16、16、26。总和为58

In my code, I'm getting weird outputs like "16, 1245782582792, 1". 在我的代码中,我得到了奇怪的输出,例如“ 16,1245782582792,1”。

Note: I can only use ifs/else, for/while loops, and arrays for this. 注意:我只能为此使用ifs / else,for / while循环和数组。

#include <stdio.h>

There are a few problems here: 这里有一些问题:

  1. You should only examine the array entries that are defined. 您应该只检查定义的数组条目。 Instead, you are looking at the entire array, including the undefined portion from nNumbers through MAX_NUMBERS-1 . 相反,您正在查看整个数组,包括从nNumbersMAX_NUMBERS-1的未定义部分。 You will likely pick up garbage values there. 您可能会在那里捡垃圾值。 Change your for loops to: for循环更改for

     for (i = 0; i < nNumbers; i++) 
  2. You are initializing greatest1 , etc. to the first number in the array. 您正在将greatest1等初始化为数组中的第一个数字。 That doesn't work if the number is odd and happens to be large enough to block the even number you're looking for. 如果数字为奇数并且碰巧足以阻止您要查找的偶数,则该方法将不起作用。

  3. If one of the largest even numbers occurs more than once, you will ignore the duplicates. 如果最大偶数之一出现多次,则将忽略重复项。 For instance, if the largest number is 1000, and it occurs three times, you probably want to add all three and return 3000. You can fix this by keeping track of the indices you have chosen, and only rejecting a duplicate if the index matches, rather than the value. 例如,如果最大数字是1000,并且发生了3次,则您可能希望将所有三个数字相加并返回3000。可以通过跟踪所选索引来解决此问题,并且如果索引匹配则仅拒绝重复项,而不是价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM