2015-05-19 48 views
4

我正在參加在線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); 
    } 
} 

我已經得到了該方案同時顯示奇數&甚至數字,它的出現。

我被卡住的唯一部分是讓程序只顯示最大的偶數位,並且它的出現。我試過的所有東西都破壞了程序的邏輯,或者產生了一些奇怪的輸出。

我應該如何繼續的任何提示或想法?

提前致謝。

+1

只需按降序(8,6,4)檢查偶數位並打印並打破,如果'myArr [x]> 0' – rohit89

+1

您可以使用數組10來存儲計數,當用戶退出時發現最大計數然後打印索引 – Subinoy

+0

輕微:注意:如果myValue == INT_MIN代碼有問題。 – chux

回答

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 
    } 

} 

注意:要優化你應該計數和存儲偶數位的出現次數。

+0

謝謝,實施if語句來檢查最大的偶數是否是最有效的? – Dumbfoundead

+0

不。我們的想法是從最大的可能的數字開始檢查,即'8'。如果出現'8',那麼計數就是我們的答案,我們會中斷。如果沒有發生'8',我們檢查下一個最大甚至數字是'6'等等。 –

+0

啊,謝謝!我明白現在休息的用法。 :) – Dumbfoundead

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]應該是其出現次數的數量。