Not working right, else is getting error.

``````#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;

int main()
{
// Declare variables below here
int CORRECT, WRONG;
double a, b, correct, result;

cout <<"Let's practice addition or subtraction with random integer numbers <100"<<endl;
cout <<"---------------Math Club--------------" << endl;
cout <<"b.  Practice subtraction"<<endl;
srand(time(0));
int Ans;
do
{   a= rand()%100;
b= rand()%100;
cin>> choice;

switch (choice)
{  case 'a': cout << a << "+" << b << "= ?";
cin >> result;
correct=a+b;
if (correct == result)
cout << "Correct\n";
cout << "Continue(y/n)?" << answer << endl;
else
cout << "Wrong" << endl;      break;
case 'b': cout << a << "-" << b << "= ?";
cin >> result;
correct=a-b;
if (correct == result)
cout << "Correct\n";
cout << "Continue(y/n)?" << answer << endl;
else
cout << "Wrong" << endl;      break;
}

cout << "Number of CORRECT answers: " << CORRECT << endl;
cout << "Number of WRONG answers: " << WRONG << endl;

system("pause");
return 0;

}
``````

There are several problems with this code :

(i) you are using double's which can represent non-integer numbers. The problem with that is if you say `if (a==b)` but actually a=3.00000000001 and b=3.000000000000000, they are not equal. When you do arithmatic between two numbers you are certain to have "round-off …

## All 2 Replies

There are several problems with this code :

(i) you are using double's which can represent non-integer numbers. The problem with that is if you say `if (a==b)` but actually a=3.00000000001 and b=3.000000000000000, they are not equal. When you do arithmatic between two numbers you are certain to have "round-off error" this occures because the accuracy of the number is limited and by increasing/decreasing the size the least significant bits are dropped/added.

The solution is to (a) not to use double's , (b) put a test to say if the result is approximately correct e.g. `if (fabs(result-correct)<1e-6)` [note the fabs function gets the absolute (positive) value so even if correct is a little bit bigger than result it works].

(ii) You write out CORRECT and WRONG but they are (a) not initialised (you now have no idea what they start as) and (b) not incremented.

(iii) your code that test for correctness is repeated -- have a look at removing it from the switch statement.

(iv) I don't see were the `do {` is closed, I expected a `} while (...);` somewhere.

Another minor point, you tell the user you're using integers but you're using doubles.

A side note,multiplying the second term by -1 will change the operation from addition to subtraction. This is helpful in that you can now use 1 function to do either operation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.