2017-12-08 2 views
-4

fnord 기능재귀 함수?

누군가 이 코드가 정확히 무엇인지 설명하십시오. 그것은 나를위한 일이지만 잘 이해할 수는 없습니다.

나는 그것을 시도했다. 0에서 9 사이의 값을 입력하면 같은 값이 반환됩니까? 메인 함수에서

double fnord(double v){ 
    int c = getchar(); 
    if(c>='0' && c<='9') 
     return fnord(v*10+(c-'0')); 
    ungetc(c,stdin); 
    return v; 
} 

나는 이렇게 한 :

int main(){ 
    double v; 
    scanf("%lf",&v); 
    printf("%lf",fnord(v)); 
} 
+1

단계 디버거를 사용하고 더 큰 값을 시도하십시오. – dbush

+0

'./myprog 123'을 시도한 다음'4','5','6'을 입력하십시오. –

답변

0
#include <stdio.h> 

// convert typed characters to the double number 
// stop calculations if non digit character is encounter 
// Example: input = 123X<enter> 
// the first argument for fnord for will have a value 
// 0*10 + 1 (since '1' = 0x31 and '0' = 0x30) 
// then recursive function is called with argument 1 
// v= 1 
// and digit '2' is entered 
// v = 1*10 + 2 ((since '2' = 0x32 and '0' = 0x30) 
// v= 12 and fnord will process third character '3' = 0x33 
// v = 12*10 +3 
// when 'X' is encountered in the input the processing will stop, (X is returned back to the input string) 
// and when ENTER is ecountered the last calculated v is returned 
// v = 123 as the double number. 

double fnord(double v){ 
    int c = getchar(); 
    if(c>='0' && c<='9') 
     return fnord(v*10+(c-'0')); 
    ungetc(c,stdin); 
    return v; 
} 

int main() 
{ 
    double v=0; 
    printf("%f",fnord(v)); 
    return 0; 
} 

INPUT :

123X 

출력 :와 코드를 통해

123.000000