473,324 Members | 2,178 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

-atof- function , example from section 4.2 K&R2

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. 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) and (power *= 10.0). these loops
using variables "val" and "power" are pretty much the work of people with
high IQs. After some work I can understand them but I can not create them
at very 1st place, I dont have that kind of thinking.

These tricks never came to my mind. Is this what we call programming ? if
yes, it is pretty much harder to come to my mind, may be never. I just do
not think this way.

Apr 4 '08 #1
6 2780

On Fri, 04 Apr 2008 12:42:14 +0530, arnuld <lo*****@shooting.com>
wrote:
>This is the example from section 4.2, page 71 of K&R2:
<snip>
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
*/
}
<snip>
>I can't really think of that kind of clever-tricks shown here...

These tricks never came to my mind. Is this what we call programming ?
Programming is an iterative process. How many iterations you want to
make is up to you to some extent but may also be impacted by
performance or memory requirements.

I've singled out one section of the code you posted since the comment
you added shows that you see what is happening.

The purpose of this section is to determine the integer portion of the
string (after all leading white space has been skipped).

A person taking their first stab at this part of the code might write:

val = 0.0;
while(isdigit(s[i]))
{
val *= 10.0;
val += s[i] - '0';
i++;
}

Some people might stop here because the code is clear and does what it
is supposed to. However, there is a school of thought that the best
way to write maintainable code is to have the code be as tight as
possible. Code will be better understood by the next person if each
line does one straightforward thing. (This can be problematic because
code that is too tight might also be too cryptic - a good programmer
strikes the proper balance.)

This code can be easily tightened up to:
val = 0.0;
while(isdigit(s[i]))
val = val * 10.0 + s[i++] - '0';

Again, some might stop here. But look at what the code does: we have
an initialization, a test for exit, a process, and an increment. That
is the definition of the for loop. Which leads to the code in K&R.
Apr 4 '08 #2
CBFalconer said:

<snip>
>
Also consider how much clearer the whole routine becomes when the
extra vertical clutter is removed:
Consider how much clutter you have left, both vertical and horizontal!

Before:
double atof(char s[]) {
int i, sign;
double val, power;

for (i = 0; isspace(s[i]); ++i) continue; /* skip whitespace */

sign = ((s[i] == '-') ? -1 : 1);
if (s[i] == '+' || s[i] == '-') ++i; /* skip any leading sign */

for (val = 0.0; isdigit(s[i]); ++i)
val = (10.0 * val) + (s[i] - '0'); /* evaluate */

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'); /* eval post decimal */
power *= 10.0;
}
return sign * val / power;
}
After (and tested, btw):

double atof(char*s){int i=0,n=0;double v=0,p=
1;while(isspace(*s))++s;if(*s){n=(*s!='-')*2-
1;(*s=='+'||*s=='-')&&++s;while(isdigit(*s))v
=(10.0*v)+(*s++-'0');if(*s=='.')while(isdigit
(*++s))(v=10.*v+*s-'0'),p*=10;}return n*v/p;}
(this is one of my fetishes)
Then presumably you are now doubly thrilled.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Apr 4 '08 #3
"arnuld" <lo*****@shooting.comwrote in message
news:pa*********************************@shooting. com...
This is the example from section 4.2, page 71 of K&R2:
[snip of tweaked exercise]
I can't really think of that kind of clever-tricks shown here. 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) and (power *= 10.0). these loops
using variables "val" and "power" are pretty much the work of people with
high IQs. After some work I can understand them but I can not create them
at very 1st place, I dont have that kind of thinking.
You don't have to be a genius of any sort to think of this sort of thing.
Each subsequent digit is ten times larger than the one that preceded it. We
learned that in grade school.
These tricks never came to my mind. Is this what we call programming ? if
yes, it is pretty much harder to come to my mind, may be never. I just do
not think this way.
If you should happen to write down using pencil and paper the steps you go
through to recognize the value of a number, then these same steps will work
when you make the computer do them. You are making this problem much harder
than it really is. If you put the book out of sight and write your own
version, you will find it is remarkably similar to theirs.

My answer to this exercise is on Richard Heathfield's site.

--
Posted via a free Usenet account from http://www.teranews.com

Apr 4 '08 #4
Dann Corbit said:
"arnuld" <lo*****@shooting.comwrote in message
news:pa*********************************@shooting. com...
>This is the example from section 4.2, page 71 of K&R2:
[snip of tweaked exercise]
>I can't really think of that kind of clever-tricks shown here. 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) and (power *= 10.0). these loops
using variables "val" and "power" are pretty much the work of people
with
high IQs. After some work I can understand them but I can not create
them at very 1st place, I dont have that kind of thinking.

You don't have to be a genius of any sort to think of this sort of thing.
Each subsequent digit is ten times larger than the one that preceded it.
We learned that in grade school.
>These tricks never came to my mind. Is this what we call programming ?
if yes, it is pretty much harder to come to my mind, may be never. I
just do not think this way.

If you should happen to write down using pencil and paper the steps you
go through to recognize the value of a number, then these same steps will
work
when you make the computer do them. You are making this problem much
harder
than it really is. If you put the book out of sight and write your own
version, you will find it is remarkably similar to theirs.

My answer to this exercise is on Richard Heathfield's site.
Well, it was. It's on a site that I once used, but no longer have write
access to (and haven't had for some years!). When I closed that account, I
shipped everything over to Flash Gordon's clc-wiki site, which can be
found here: http://clc-wiki.net/wiki/

Your solution is at this URL:

<http://clc-wiki.net/wiki/K%26R2_solutions%3AChapter_4%3AExercise_2>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Apr 4 '08 #5
da*****@excite.com wrote:
>
.... snip ...
>
This code can be easily tightened up to:
val = 0.0;
while(isdigit(s[i]))
val = val * 10.0 + s[i++] - '0';

Again, some might stop here. But look at what the code does:
we have an initialization, a test for exit, a process, and an
increment. That is the definition of the for loop. Which leads
to the code in K&R.
And that tightening can lead to an error. The term "s[i++] - '0'"
should be firmly wrapped in a set of parenthesis. Otherwise errors
can occur when the magnitude of val suddenly exceeds a magic
threshold, and the subtraction of '0' does not work correctly.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Apr 4 '08 #6
Richard Heathfield wrote:
CBFalconer said:

<snip>
>>
Also consider how much clearer the whole routine becomes when the
extra vertical clutter is removed:

Consider how much clutter you have left, both vertical and horizontal!

Before:
>double atof(char s[]) {
int i, sign;
double val, power;

for (i = 0; isspace(s[i]); ++i) continue; /* skip whitespace */

sign = ((s[i] == '-') ? -1 : 1);
if (s[i] == '+' || s[i] == '-') ++i; /* skip any leading sign */

for (val = 0.0; isdigit(s[i]); ++i)
val = (10.0 * val) + (s[i] - '0'); /* evaluate */

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'); /* eval post decimal */
power *= 10.0;
}
return sign * val / power;
}

After (and tested, btw):

double atof(char*s){int i=0,n=0;double v=0,p=
1;while(isspace(*s))++s;if(*s){n=(*s!='-')*2-
1;(*s=='+'||*s=='-')&&++s;while(isdigit(*s))v
=(10.0*v)+(*s++-'0');if(*s=='.')while(isdigit
(*++s))(v=10.*v+*s-'0'),p*=10;}return n*v/p;}
>(this is one of my fetishes)

Then presumably you are now doubly thrilled.
Well, Chuck's version is more readable than your _and_ more readable that
the OP's

Bye, Jojo
Apr 5 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: int2str | last post by:
All, As the simple sample program below demonstrates, function arguments are destroyed after the return value of the function has been evaluated. As opposed to local function variables, which...
19
by: Deniz Bahar | last post by:
Hi, I would like to call one of my functions the exact name as an existing C library function (for example K&R2 exercises asks me to make an atof function). If I don't include the header with...
1
by: John Mark Howell | last post by:
When using the example straight out of the MSDN and using the Visual Studio 2003's Build Comment Web Pages, you will not see the <example> section. It is in the generated XML file but I do not see...
21
by: oksuresh | last post by:
Hi talents, I have noticed that atof() function approximates the string I pass to it. when I use atof() , as atof(" 184.64") and it returns 184.63999999999 But I would like to have...
5
by: tjay | last post by:
Hi. I wrote some code using sprintf and atof to store a double as a string of fixed length and to convert it back to a double variable. The string is stored in a char buffer global variable. I'm...
14
by: sharmaharish | last post by:
I need a conversion function that converts values from string to a particular type. For this I have a template function that looks like this ... template<class T> T value(const string& s) {...
8
by: Scott M. | last post by:
Where will code that is preceded with: /// <example> /// some comments /// </example> actually show up? I can see my <summaryand <remarkscode showing up in the code comment pages and in...
3
by: muler | last post by:
hi all, After reading this excerpt from "The C# Programming Language", (By Anders) I tried to check it out. Unfortunately, I'm getting compile errors. Can anyone illustrate this with an...
14
by: Nickolay Ponomarev | last post by:
Hi, Why does http://www.jibbering.com/faq/ uses new Function constructor instead of function expressions (function(...) { ... }) when defining new functions? E.g. for LTrim and toFixed. Is the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.