On 4 Apr, 08:12, arnuld <loot...@shooting.com> wrote:
> This is the example from section 4.2, page 71 of K&R2:
>
> double atof( char s[] )
> {
> * int i, sign;
> * double val, power;
>
> * for( i = 0; isspace( s[i] ); ++i )
> * * {
> * * * /* skipe the leading whitespace */
> * * }
>
> * sign = ( (s[i] == '-') ? -1 : 1 );
>
> * if( s[i] == '+'|| s[i] == '-' )
> * * {
> * * * ++i;
> * * * /* skip the leading sign, of any */
> * * }
>
> * for( val = 0.0; isdigit( s[i] ); ++i )
> * * {
> * * * val = (10.0 * val) + (s[i] - '0');
>
> * * * /* s[i] - '0' (zero in quotes)
> * * * ** always gives "int i" as output
> * * * **/
> * * }
>
> * if( s[i] == '.' )
> * * {
> * * * ++i;
> * * * /* skip the dot(.) of a floating point */
> * * }
>
> * for( power = 1.0; isdigit( s[i] ); ++i )
> * * {
> * * * val = (10.0 * val) + (s[i] - '0');
> * * * power *= 10.0;
> * * }
>
> * return sign * val / power;
>
> }
>
> I can't really think of that kind of clever-tricks shown here.
I didn't think they were *that* clever
> checking
> for leading space and dot (.) are fine,they are very general things and
> easily come to my mind but look at how cleverly the K&R created the
> expressions *like (val = 10.0 * val)
how *else* would you code that?
> and (power *= 10.0).
which is just short hand for power = power * 10;
these seem fairly easy to me, but then I was weaned
on stuff like this. Some of it in Fortran...
> these loops
> using variables "val" and "power" are pretty much the work of people with
> high IQs. *
weel I don't foubt the Mr R has a high IQ, but I don't
see the examples you give as demonstrating it.
The trick is to look for patterns (that's about half
the job of programming). The power one is just stepping
through powers of 10 (1, 10, 100, 1000...).
> After some work I can understand them but I can not create them
> at very 1st place, I dont have that kind of thinking.
the trick is to catch repititions in your program text and
then trying to come up with a pattern that eliminates the
repetition.
> These tricks never came to my mind. Is this what we call programming ?
part of the job.
> if
> yes, it is pretty much harder to come to my mind, may be never. I just do
> not think this way.
all I can suggest it practice. Maybe have a look at
http://mitpress.mit.edu/sicp/
(it can be hard going so try the online version
before you consider buying)
--
Nick Keighley