@
MienTommy
Just wanted to mention that this will almost never work :
1 2
|
else if (donations[i] == averageDonations)
donEquAvg;
|
Doubles are stored as binary fractions and cannot exactly represent every real number, even ones like 0.1, so equality tests like this will certainly fail.
To test for equality within a certain precision, check the absolute value of the difference between the 2 numbers, is less than the precision :
1 2 3 4 5 6 7 8
|
const double PRECISION = 0.001;
if(std::abs(donations[i] - averageDonations) < PRECISION ) {
std::cout << "The two values are equal within " << PRECISION << "\n";
}
else {
std::cout << "The two values are not equal." << "\n";
}
|
However, with your code, you have already tested for less than & greater than, so the only other remaining possibility is that of equality, so this should be with an else clause - not else if. On line 34, you didn't increment the
donEquAvg
variable, but as I said, this line would never be executed any way.
There is also this value :
std::numeric_limits<double>::epsilon()
Which is the difference between 1.0 and the next representable number. You should scale this value up for the number range you want to use. For example, if your number is 1000.0 then the epsilon for it would be :
constexpr double Epsilon1000 = 1000.0 * std::numeric_limits<double>::epsilon();
C++11 also has functions like
std::nextafter
& variations of, described here:
Another pedantic thing : If I mean to use a double, then I always specify them explicitly as doubles, like this :
averageDonations = totalDonations / 10.0;
Except that I would do this, to avoid "magic numbers" throughout the code:
1 2
|
averageDonations = totalDonations / static_cast<double>(donations.size);
|
Because you are using vectors, you should consider using a while loop instead of a for loop. The end condition would some sentinel value like zero say.
If you were using a fixed size container like an array for example, then make use of const declared variables, like this :
1 2 3
|
const int SIZE = 10;
double Donations[SIZE];
|
Line 20 should be
else
not
else if
because the
cin
either works or it doesn't. The exit on line 23 is rather rude - make one mistake and the program terminates!
There are other things to check - like cin.fail, and make use of a while loop until good input is achieved.
Hope all this helps - I look forward to seeing how you get on. 8+)