Can we improve the below code? Chapter 5 exercise from 2 to 4

61 views
Skip to first unread message

Shashank

unread,
May 20, 2012, 8:14:16 AM5/20/12
to PPP-public
Hello Team,

I am back with questions :)

Can we improve the below code? Chapter 5 exercise from 2 to 4


//This program converts celsius to kelvin.
#include"../../../std_lib_facilities.h"
//pre condition: argument cel must be a floating point value
//post condition: function should return the floating point value
const double temp=273.15;
double celsiusTokelvin(double cel)
{
if(cel<=-temp)
error("please enter the valid temperature:\n");
double Kelv;
Kelv=cel+temp;
return Kelv;
}

int main()
{
double input_celsius;
cout<<"Enter the float value in celsius:\n";
cin>>input_celsius;
/*if(input_celsius<=-temp)
error("please enter the valid temperature:\n");*/
double result_kelvin=celsiusTokelvin(input_celsius);
cout<<input_celsius<<" celsius is "<<result_kelvin<<" kelvin:\n";
keep_window_open();
return 0;
}

Bharath Jayaraman

unread,
May 21, 2012, 11:13:38 AM5/21/12
to ppp-p...@googlegroups.com
Hi shashank
Actually u need not perform the celsius check again inside the
function since you have already checked it in the main function.
Good day.
> --
> You received this message because you are subscribed to the Google Groups "PPP-public" group.
> To post to this group, send email to ppp-p...@googlegroups.com.
> To unsubscribe from this group, send email to ppp-public+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/ppp-public?hl=en.
>

Vivekanand P V

unread,
May 22, 2012, 12:06:59 AM5/22/12
to PPP-public
Dear Bharath,

Though Shashank might have removed it, he has commented out the
condition check in main. It is hence ineffectual.

Regards,
V



On May 21, 8:13 pm, Bharath Jayaraman <senseoffende...@gmail.com>
wrote:

Shashank

unread,
May 22, 2012, 8:50:18 AM5/22/12
to PPP-public
Hi,

Thank you for the inputs :)

Art Werschulz

unread,
May 22, 2012, 4:20:47 PM5/22/12
to ppp-p...@googlegroups.com
Hi all.

On May 20, 2012, at 8:14 AM, Shashank wrote:

> //This program converts celsius to kelvin.
> #include"../../../std_lib_facilities.h"
> //pre condition: argument cel must be a floating point value

Allow me to be a little fussy here.

I would put "none" for a precondition. Looking at the argument list, it's obvious that cel must be a floating point value. By way of contrast, suppose you wanted to compute a letter grade as a function of a numerical grade; you might well require the numerical grade to be in the range [0, 100], and so this would be a precondition for the function.

> //post condition: function should return the floating point value

A post-condition usually refers to an effect of a function call upon the operating environment. For instance, if you were to write your own function to sort the elements of a vector, the postconditon would say that the elements are sorted, e.g., you might write something like

// sort a vector using the foosort algorithm
// precondition: none
// postcondition: a[0] <= a[1] <= ...<= a[n-1], where n = a.size()
void mysort(vector<double> a) { ... }

> const double temp=273.15;

Choose a better name. Moreover, the number 273.15 doesn't mean all that much, but its negative is absolute zero (in degrees Celsius), which is meaningful. So I'd do
const double absolute_zero = -273.15; // degrees Celsius

> double celsiusTokelvin(double cel)

Be consistent in how you write compound words used for names of things. Either write celsiusToKelvin or celsius_to_kelvin. The choice between the latter is a religious argument (akin to Mac vs. Windows vs. Linux, or emacs vs. vi). Bjarne prefers the latter. The book I use for teaching data structures prefers the former. I've tended to use the former, but I don't really have any dog in this fight. To minimize confusion, I tell my students to follow the standard of whatever text we're using.

Also, use "celsius" rather than "cel". It's not that much more typing, since it only appears a few times, and it improves readability.

> {
> if(cel<=-temp)
> error("please enter the valid temperature:\n");

You're telling the user to enter a temperature, but you're not giving him a chance to do so. That's somewhat misleading, and may mystify your user.

> double Kelv;

Why the capital "K" here? You don't put a capital "C" when you talk about Celsius temperatures. Moreover, you're running afoul of the author's coding standard, which more or less states that names of data types should begin with a capital letter and that names of other things start with a lower case letter. (In that way, you can instantly tell whether a name refers to a data type or to anything else.)

Also, I'd use "kelvin", rather than "kelv". It doesn't take that much effort to type the extra two characters, and it certainly improves the readability. Bjarne talks about this in the text.

> Kelv=cel+temp;
> return Kelv;
> }
>
> int main()
> {
> double input_celsius;
> cout<<"Enter the float value in celsius:\n";
> cin>>input_celsius;
> /*if(input_celsius<=-temp)
> error("please enter the valid temperature:\n");*/

Although your conversion function checks for a invalid parameter, it's still a good idea for the calling environment to check the validity of any actual arguments, whenever this is practical. (Also, it's good practice for situations in which different programmers wrote the conversion function and main.) Call it "belt-and-suspenders", if you like.

You might wonder when it might be impractical to check for a valid argument. The answer: when doing so would be overly complex or time-consuming. The classical case? If a vector is in proper order, then binary search can be used instead of linear search, thereby gaining an exponential speedup; however, if the binary search routine checks the the vector is in order, then you lose the speedup.

> double result_kelvin=celsiusTokelvin(input_celsius);
> cout<<input_celsius<<" celsius is "<<result_kelvin<<" kelvin:\n";
> keep_window_open();
> return 0;
> }

Personal preference: A lot of people think that putting a space on either side of an operator improves readability. The only exception would be for multiplicative operators, based on traditional mathematical typesetting. So I'd tend to write "a + b", but "c*d".

I'm attaching my solution to this msg. For fun, I added a loop in main() that rejects invalid Celsius temperatures. The program is not bullet-proof; if you give it "asdf" as the Celsius temperature, it simply uses 0. That kind of thing is for later on.

Art Werschulz (8-{)} "Metaphors be with you." -- bumper sticker
GCS/M (GAT): d? -p+ c++ l u+(-) e--- m* s n+ h f g+ w+ t++ r- y?
Internet: agw STRUDEL comcast.net

temperatures.cc

Bharath Jayaraman

unread,
May 24, 2012, 9:17:51 AM5/24/12
to ppp-p...@googlegroups.com
damn me...i should have seen that...no excuses for my mistake...
and yeah thanks for pointing out that V.I didnt notice that and just
ignored it..another lesson i wont forget

Vivekanand P V

unread,
May 24, 2012, 9:36:35 AM5/24/12
to PPP-public
Never mind. Such things happen. :-)

On May 24, 6:17 pm, Bharath Jayaraman <senseoffende...@gmail.com>
wrote:
> damn me...i should have seen that...no excuses for my mistake...
> and yeah thanks for pointing out that V.I didnt notice that and just
> ignored it..another lesson i wont forget
>

Art Werschulz

unread,
May 24, 2012, 9:55:33 AM5/24/12
to ppp-p...@googlegroups.com
Hi.

On May 24, 2012, at 9:36 AM, Vivekanand P V wrote:

> Though Shashank might have removed it, he has commented out the
> condition check in main. It is hence ineffectual.

I would guess that this condition check in main was for testing purposes, and that Shashank commented it out after the conversion function passed its tests.

Even so, many people like to leave commented-out debugging code within the program. Suppose that a program gets modified; it's not a bad idea to redo old test cases after the modification is made. Also, you sometimes see debugging code contained within a #ifdef/#endif preprocessor block, so that the code could go into debugging mode after a recompilation. Better yet, you can put debugging code within something like
if (debugging) { ... }
where debugging can be set via command-line parameters.

So in any case, it's not such a bad idea to keep commented-out checks within your code.

Vivekanand P V

unread,
May 24, 2012, 9:56:27 PM5/24/12
to PPP-public
>     if (debugging) { ... }
> where debugging can be set via command-line parameters.

Then come the actual functions, such as temperature_converter, where
one examines condition(s). Presumably, one needs a mutually exclusive
block here in the function, something like if (!debugging). Inevitably
this device raises the code complexity, making the code vulnerable. I
must say the complexity must be seen in the context of requirements
and program design, though. As far as one can see, the wisdom (if I
can use such a word) lies in making things simple and clear.

V

Art Werschulz

unread,
May 24, 2012, 10:32:30 PM5/24/12
to ppp-p...@googlegroups.com
Hi.

On May 24, 2012, at 9:56 PM, Vivekanand P V wrote:

> Then come the actual functions, such as temperature_converter, where
> one examines condition(s). Presumably, one needs a mutually exclusive
> block here in the function, something like if (!debugging). Inevitably
> this device raises the code complexity, making the code vulnerable.

Absolutely. There's always a conflict between simplicty and generality. BTW, some apps take a debugging level as a command line parameter (dvips comes to mind here), allowing one to print debug info about specific items of interest.

> I must say the complexity must be seen in the context of requirements
> and program design, though. As far as one can see, the wisdom (if I
> can use such a word) lies in making things simple and clear.

"Perfection is reached not when there's nothing left to add, but when there's nothing left to remove." - Antoine de St. Exupery.

"There are two ways of constructing a software design: one way is to make it so simple that there are *obviously* no deficiencies
and the other way is to make it so complicated that there are no *obvious* deficiencies."
C.A.R. Hoare "The Emperor's Old Clothes" CACM Feb 1981
Reply all
Reply to author
Forward
0 new messages