如何在C中找到3个最大的偶数?

时间:2021-03-31 21:30:01

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>

1 个解决方案

#1


3  

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. You will likely pick up garbage values there. Change your for loops to:

    您应该只检查定义的数组条目。相反,您正在查看整个数组,包括从nNumbers到MAX_NUMBERS-1的未定义部分。你可能会在那里拿起垃圾值。将for循环更改为:

    for (i = 0; i < nNumbers; i++)
    
  2. You are initializing greatest1, etc. to the first number in the array. That doesn't work if the number is odd and happens to be large enough to block the even number you're looking for.

    您正在将maximum1等初始化为数组中的第一个数字。如果数字是奇数并且碰巧大到足以阻止你正在寻找的偶数,那么这不起作用。

  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,并且它出现三次,您可能想要添加所有三个并返回3000.您可以通过跟踪您选择的索引来解决此问题,并且只有在索引匹配时才拒绝重复而不是价值。

#1


3  

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. You will likely pick up garbage values there. Change your for loops to:

    您应该只检查定义的数组条目。相反,您正在查看整个数组,包括从nNumbers到MAX_NUMBERS-1的未定义部分。你可能会在那里拿起垃圾值。将for循环更改为:

    for (i = 0; i < nNumbers; i++)
    
  2. You are initializing greatest1, etc. to the first number in the array. That doesn't work if the number is odd and happens to be large enough to block the even number you're looking for.

    您正在将maximum1等初始化为数组中的第一个数字。如果数字是奇数并且碰巧大到足以阻止你正在寻找的偶数,那么这不起作用。

  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,并且它出现三次,您可能想要添加所有三个并返回3000.您可以通过跟踪您选择的索引来解决此问题,并且只有在索引匹配时才拒绝重复而不是价值。