Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy Division/Math Question for C++

Status
Not open for further replies.

gonzilla

Programmer
Apr 10, 2001
125
US
Hi,

If my declarations are this:

#define TAmt 0.40

int main(void)
{
double MTot=0.0;
....
MTot+=TAmt;
...
}

Let's say I hit this incrementing statement 5 times in the same program, so MTot is 2.00. If I divide MTot by TAmt, I get 5.

cout <<(int)(Mtot/TAmt);
(I want to use a int type-cast to display an integer)

That works fine. Why then, if I hit these statements 6 times and MTot is 2.40 and do this:

cout <<(int)(Mtot/TAmt);

...I get 5!!! It works for various other numbers but most of them will be incorrect. If I remove the (int) type-cast I get the right answer in all cases, but I don't want to display 6.00, I want just 6 to display.

Obvioulsy the type-cast and precision of the double has something to do with it....what is gong on and how can I fix this?

Thanks.

-Tyler
 
The (int) type casting is rounding the 2.40 down to 2.00,
which is why you get 5 both times.

Try this:
use double values for all your variables, and do your division, then when you want to get your 6.00 value,
you can format the double to display how you like

double value = (Mtot/TAmt);
CString temp;
temp.Format(&quot;%.2f&quot;,value);
You'll have the desired output in a string variable.
Let me know if that helps.

 
sorry, you may need to do temp.Format(&quot;%f',value);
 
sorry, you may need to do temp.Format(&quot;%f&quot;,value);
 
I thought if I surrounded the (MTot/TAmt) it would do that first and then type-cast it to int? Isn't that true?

Also,

Should I be using:

const double TAmt=0.40000000

instead of the #define?

-Tyler
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top