2017-12-08 18 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 

OUTPUT:を有するコードを介して

123.000000