1

We have a school assignment and we were told that all numbers end after the third decimal digit, meaning 0.0009 is 0 in our case. How can I do that in c++? Should I create a new class using operator overloading? Thanks

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
yotamoo
  • 5,334
  • 13
  • 49
  • 61

5 Answers5

3

You should be able to take your number, multiply by 1000, perform your arithmetic operation and then divide by 1000.0 to get your result.

((int)(0.0009 * 1000))/1000.0 == 0.0
Burton Samograd
  • 3,652
  • 19
  • 21
3

Should I create a new class using operator overloading?

That would help make the code that uses the class simple. It's up to you to decide whether you want to make the effort to obtain that simplicity.

How can I do that in c++?

In C++ there is a way to truncate a floating point number to zero decimal places: a cast.

double d1 = 1.34;
double d2 = (int)i; // now d2 is 1

You can use this with some math to truncate to three decimal places.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
1

You may choose to use integer numbers. Take 0.0009 * 1000 = 0.9 and only use the integer part, iow 0. At the end you can choose to divide your final answer by 1000?

Dirk
  • 1,184
  • 6
  • 22
0

For printing, I don't think new class will be needed, you can round them off. use printf("%.3f", );

See this: Rounding Number to 2 Decimal Places in C

For use in calculation, see this: http://www.daniweb.com/software-development/cpp/threads/184830

Community
  • 1
  • 1
SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67
0

For a few calculations, don't make a class - it will make the code harder to understand (any time you do operator overloading you must take into account future users making mistakes because of unexpected behavior). Having said that, you may be able to get away with a very simple class that just contains a cast-to-double and a assign-from-double operators along with a constructor. This would be perfectly acceptable.

#include <cmath>
class Threep
{
   double val;
public:
   Threep(double x) : val(floor(x*1000)/1000) {}
   operator double() { return val; }
   double operator=(double rhs) { val = floor(rhs*1000)/1000; return val;}
   double operator*=(double rhs) { val = floor((val*rhs)*1000)/1000; return val;}
   double operator/=(double rhs) { val = floor((val/rhs)*1000)/1000; return val;}
   double operator+=(double rhs) { val = floor((val+rhs)*1000)/1000; return val;}
   double operator-=(double rhs) { val = floor((val-rhs)*1000)/1000; return val;}
};

I added some convenience assignments along with operator= :-)

This code is untested but it looks good to my eye.

mheyman
  • 4,211
  • 37
  • 34