递归函数?

时间:2017-12-08 23:53:32

标签: c

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 个答案:

答案 0 :(得分: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
相关问题