Really Simple Math

  • Thread starter Thread starter Christopher Weaver
  • Start date Start date
C

Christopher Weaver

I've declared o to be a double and c an int. No matter what the value of c,
o is never greater than 0 after the following line of code:

o = (c / 100);


Any ideas why?
 
I've declared o to be a double and c an int. No matter what the value
of c, o is never greater than 0 after the following line of code:

o = (c / 100);


Any ideas why?
c/100 performs integer division. If c is less than 100 then c/100 will
be a 0. If you want the value you expect, use

o = c / 100.0 now you do floating point division.
Any introductory programming book will go over this.

(BTW, o is a poor name of a variable of 1 character length.)


--
Dennis Roark

(e-mail address removed)
Starting Points:
http://sio.midco.net/denro/www
 
Thanks. I knew it was basic. In fact, as I read your reply I recalled the
point being made in my first semester c++ class. Years of Pascal has erased
much of that.

BTW, the 'o' was included for debugging purposes only.
 
Christopher said:
I've declared o to be a double and c an int. No matter what the value of c,
o is never greater than 0 after the following line of code:

o = (c / 100);


Any ideas why?
No idea IF your claim is correct. However, I think what you really mean is "No
matter what the value of c (as long as it's less than 100), o is never greater
than 0."

The expression (c / 100) is apparently calculated using integer arithmetic,
which is perfectly reasonable since c and 100 are both integer expressions. The
integer result of this division will be zero when c is less than 100. I suggest
you test your "no matter what" claim with some larger values of c (e.g., 100,
101, 199, 200, 201, 299, etc.) and watch what happens.

-rick-
 
Personally I prefer to use:

o = c * 0.01;

Is it faster?
Perharps negligible.
 
Good point. It's so nice to have a group that pays attention and cares
enough to write.
 
Altramagnus said:
Personally I prefer to use:

o = c * 0.01;

Is it faster?
Perharps negligible.

I don't think it's nearly as clear at a glance that that's dividing by
a hundred though. Just MHO.
 
Altramagnus said:
i agree, but you can put a comment or something.

If you have to put a comment on one version to make it clearer, and you
haven't proved it to be faster, why do you prefer it? I'd take
readability over unproven speed any day.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top