Skip to content

Instantly share code, notes, and snippets.

@MathiasYde
Created February 17, 2022 16:08
Show Gist options
  • Save MathiasYde/101682c48ce77b2240d1a01719b2a918 to your computer and use it in GitHub Desktop.
Save MathiasYde/101682c48ce77b2240d1a01719b2a918 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <map>
#include <functional>
#include <iterator>
int main() {
//Define operations and their respective function
std::map<std::string, std::function<int(int, int)>> operations;
operations["+"] = [&](int lhs, int rhs) { return lhs + rhs; };
operations["-"] = [&](int lhs, int rhs) { return lhs - rhs; };
operations["*"] = [&](int lhs, int rhs) { return lhs * rhs; };
operations["/"] = [&](int lhs, int rhs) { return lhs / rhs; };
std::string _operator;
int lhs;
int rhs;
std::string useranswer;
float correctanswer;
while (true) {
// Generate random numbers
rhs = rand() % 100;
lhs = rand() % 100;
// Choose random operator
auto iterator = operations.begin();
std::advance(iterator, rand() % operations.size());
std::string _operator = iterator->first;
// Calculate correct answer
correctanswer = operations[_operator](lhs, rhs);
std::cout << "Solve:" << std::endl;
std::cout << lhs << " " << _operator << " " << rhs << std::endl;
std::cin >> useranswer;
if (stoi(useranswer) == correctanswer) {
std::cout << "Correct!" << std::endl;
} else {
std::cout << "Wrong, correct answer is " << correctanswer << std::endl;
}
std::cout << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment