473,782 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

-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 2809

On Fri, 04 Apr 2008 12:42:14 +0530, arnuld <lo*****@shooti ng.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){in t i=0,n=0;double v=0,p=
1;while(isspace (*s))++s;if(*s) {n=(*s!='-')*2-
1;(*s=='+'||*s= ='-')&&++s;while(i sdigit(*s))v
=(10.0*v)+(*s++-'0');if(*s=='.' )while(isdigit
(*++s))(v=10.*v +*s-'0'),p*=10;}ret urn 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*****@shooti ng.comwrote in message
news:pa******** *************** **********@shoo ting.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*****@shooti ng.comwrote in message
news:pa******** *************** **********@shoo ting.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_solution s%3AChapter_4%3 AExercise_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){in t i=0,n=0;double v=0,p=
1;while(isspace (*s))++s;if(*s) {n=(*s!='-')*2-
1;(*s=='+'||*s= ='-')&&++s;while(i sdigit(*s))v
=(10.0*v)+(*s++-'0');if(*s=='.' )while(isdigit
(*++s))(v=10.*v +*s-'0'),p*=10;}ret urn 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
2041
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 are destroyed before the function returns. Is this correct? (To the best of my knowledge it is) Where in the standard is this described?
19
2515
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 the declaration for the C library function (stdlib.h in this case) then define/declare my own function with the same name, am I safe? It seems to work on my compiler, but I wonder if this is portable or even acceptable? thx
1
1657
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 it in the VS window. Does anyone know how to get that to show up? A second question is where is the XSL and CSS that VS is using to display the XML? Try the following example straight from the MSDN help: /// <summary>
21
8366
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 the exact value that is passed.
5
3203
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 afraid it might contain bugs though. If I serialize a double, I get a string of the format "-1.0000000000000000e+212". This string gets stored in the buffer. Then, to convert it back into a double, I pass it to the atof function. The problem...
14
8918
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) { istringstream(s); T val; is >val;
8
1892
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 the Object Browser, but where will the example come into play?
3
4795
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 example: ---------------------------------------------------- Section 7.7.4 - enumeration addition
14
1558
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 reason that you want to avoid accidental closures? Or does some obscure browser does not support function expressions? This just looks weird, given that http://www.jibbering.com/faq/#FAQ4_40 says to only use eval() (which is not really much...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.