查找给定整数中的最大偶数

时间:2015-05-19 17:48:43

标签: c arrays

我正在上网C课,但教授拒绝接听电子邮件,我需要一些帮助。

无论如何,我们的任务是编写一个程序,该程序从用户获取一个整数,并找到最大的偶数位和给定整数中数字出现的次数。

#include <stdio.h>

void extract(int);
void menu(void);


int main() {
    menu();
}

void menu() {
    int userOption;
    int myValue;
    int extractDigit;

    do {
        printf("\nMENU"
            "\n1. Test the function"
            "\n2. Quit");
        scanf("%d", &userOption);

        switch (userOption) {
        case 1:
            printf("Please enter an int: ");
            scanf("%d", &myValue);

            extractDigit = digitExtract(myValue);

            break;

        case 2:
            printf("\nExiting . . . ");
            break;

        default:
            printf("\nPlease enter a valid option!");
        }
    } while (userOption != 2);
}

void digitExtract(int userValue) {
    int tempValue;
    int x;
    int myArr[10] = { 0 };

    tempValue = (userValue < 0) ? -userValue : userValue;

    do {
        myArr[tempValue % 10]++;
        tempValue /= 10;
    } while (tempValue != 0);


    printf("\nFor %d:\n", userValue);
    for (x = 0; x < 10; x++) {
        printf("\n%d occurence(s) of %d",myArr[x], x);
    }   
}

我已经让程序显示奇数和&amp;偶数和它的出现。

我坚持的唯一部分是让程序只显示最大偶数及其出现。我尝试的所有东西要么破坏了程序的逻辑,要么产生一些奇怪的输出。

关于我应该如何进行的任何提示或想法?

提前致谢。

2 个答案:

答案 0 :(得分:2)

运行从最大偶数到最小偶数的循环。

for (x = 8; x >=0; x-=2)
{
    if(myArr[x]>0) //if myArr[x]=0 then x does not exist
    {
        printf("%d occurs %d times",x,myArr[x]);
        break; //we have found our maximum even digit. No need to proceed further
    }

}

注意:要进行优化,您应计算并存储仅偶数位的出现次数。

答案 1 :(得分:0)

为什么你甚至使用额外的循环?要找到整数中最大的偶数及其出现次数,对第一个循环的修改就足够了。

考虑以下情况(未经测试,但我希望你能得到这个想法):

int tempValue;
int x;
int myArr[10] = { 0 };

int maxNum = 0;

tempValue = (userValue < 0) ? -userValue : userValue;

do {
    int currNum = tempValue % 10;

    myArr[currNum]++;
    tempValue /= 10;

    if (currNum % 2 == 0 && currNum > maxNum)
        maxNum = currNum;
} while (tempValue != 0);

在此之后,maxNum应该包含最大的偶数,myArr[maxNum]应该是其出现的数量。

相关问题