2017-07-01 24 views
0
#include <stdio.h> 
//Compiler version gcc 6.3.0 
void print(int a[5],int n){ 
    n--; 
    if(a[n]%2==0) 
     print(a,n); 
    printf("%d",a[n]); 
} 
int main(void){ 
    int a[] = {1,2,3,4,5}; 
    print(a,5); 
    return 0; 
} 

你將如何打印該數組中的偶數......通過最後一個元素顯然,代碼不起作用,所以如何去做呢?如何使用右側的遞歸遍歷來打印數組中的偶數?

回答

2

即使號碼是奇數,或者遞歸停止,您也必須致電print

當值爲偶數時也只有printf,並且當n索引爲負數或您有訪問衝突時停止。

修正:

void print(int a[],int n) 
{ 
    n--; 
    if (n>=0) 
    { 
    print(a,n); 
    if(a[n]%2==0) 
    { 
     printf("%d ",a[n]); 
    } 
    } 
} 

打印:2 4

+0

這是你會怎麼做它的制約下?或者因爲我是那樣?你乾淨的版本是什麼? –

+0

我想是的。但是,如果你問我,這些限制是荒謬的:) –

+0

是,這是使用遞歸打印dp問題的解決方案。而不是直接發佈,我認爲我會學習和應用在那裏。 –