I need some help with this code, its a random sum generator that does subtraction. I want it to only generate sums that equal a positive number and not ones that generate a negative number.
Any ideas how id make that work with the code below?
Any help is appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <string>
#include <sstream>
#include <ctype.h>
#include <string.h>
usingnamespace std;
int main()
{
cout << "Mash your keyboard to exit!" << endl;
cout << " " << endl;
int a = 0;
int b = 0;
int sum = 0;
int x = 0;
while (true) // Keeps going until you get a right answer
{
srand((unsigned)time(NULL));
a = 1 + (rand() % 10);
b = 1 + (rand() % 10);
sum = a - b;
cout << a;
cout << " - ";
cout << b << endl;
cout << "The answer is ";
cin >> x; // Takes in a type int as x is defined as an int
if (x != sum)
{
cout << "That is not the right answer! " << endl;
cout << "The correct answer is " << sum << endl;
cout << " " << endl;
}
if (cin.fail()) // Checks if input for a valid type
{
cout << "That is not a number! Numbers only. " << endl;
cout << " " << endl;
system("pause"); // If you want to keep going remove these to lines.
break;
}
if (x == sum)
{
cout << "That is the correct answer! " << endl;
cout << " " << endl;
}
}
return 0;
}
I tried that code and it does work very well, with one problem, when a sum changes from' a-b' to 'b-a' it still calculates 'a-b'. So even if I type in the correct answer for what the computer tells me it still says i'm wrong. Any idea how to fix this?
I'm fairly new to this so it could be quite simple.
Thanks.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <string>
#include <sstream>
#include <ctype.h>
#include <string.h>
usingnamespace std;
int main()
{
cout << "Mash your keyboard to exit!" << endl;
cout << " " << endl;
int a = 0;
int b = 0;
int sum = 0;
int x = 0;
while (true) // Keeps going until you get a right answer
{
srand((unsigned)time(NULL));
a = 1 + (rand() % 10);
b = 1 + (rand() % 10);
sum = a - b;
if (a < b)
std::swap(a, b);
cout << a;
cout << " - ";
cout << b << endl;
cout << "The answer is ";
cin >> x; // Takes in a type int as x is defined as an int
if (x != sum)
{
cout << "That is not the right answer! " << endl;
cout << "The correct answer is " << sum << endl;
cout << " " << endl;
}
if (cin.fail()) // Checks if input for a valid type
{
cout << "That is not a number! Numbers only. " << endl;
cout << " " << endl;
system("pause"); // If you want to keep going remove these to lines.
break;
}
if (x == sum)
{
cout << "That is the correct answer! " << endl;
cout << " " << endl;
}
}
return 0;
}
I'm not quite following you, would you be able to copy what i'm supposed to do into the code and I might understand it better.
Sorry for the inconvenience!