Hi,
Good work ! Not a bad effort for 2 days coding :+) I really like you are using
std::
already :+D
However, a couple of problems with the division part.
First is that the types are
int
, integer division doesn't help you here. 2/4 is 0 and 25/13 is 1. So you could make the types
double
, that will solve that problem.
Next, it's always a good idea to check for division by zero before you do any division, otherwise you will have infinity. With a
double
this is a little more tricky, doubles are stored as binary fractions and are not exact, so we shouldn't compare them using
==
, but we can use relational operators
<
and
>
and
<=
etc. Instead we see if it's absolute value is less than some precision value we choose. So it is "near enough" to zero for our purposes. Consider this snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <cmath>
// ...
// ...
double a = 0.1; // really 0.09999999999997 say, or 0.10000000000002
double b = 1.0 - (10.0 * a) ; // 3e-16 say if(b == 0.0) is false
const double PRECISION = 1e-4; // 0.0001 change this to whatever suits you
bool IsNearToZero = false;
if (std::abs(b) < PRECISION) {
std::cout << "b is near enough to zero, using " << PRECISION << " as precision\n";
IsNearToZero = true;
}
|
Good Luck !! And don't hesitate to ask questions :+)