功能
有人可以解释一下此代码的确切作用。这对我来说是一项任务,但我不太了解。
我尝试过这个。当我输入一个介于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));
}
最佳答案
#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;
}
输入:
123X
输出:
123.000000