Thanks all :)
Printable View
Thanks all :)
You can generate a (pseudo)random number (possibly using std::srand() and std::rand() from <cstdlib>) and map it to one of the operators (the principle is the same whether you mean merely characters or actual operations).
More like map a number to an operator. You could use an if-else chain, a switch, an array, a std::map, etc.Quote:
Originally Posted by jordieg03
When overloading the operators, the rule should always be "Do what the integers do".
For example the following code should cause someone to be shot:
Code:MyClass operator +(MyClass const &a, MyClass const &b)
{
return a.Value - b.Value;
}
TheCPUWizard has made a good point, the client should be able to clearly understand what the overloaded operators purpose is just by looking at the interface and not having to sift through the implementation to see how it really works.
If it seems unclear at what an operator does with a value, then it should be a function instead.
I believe the OP didn't ask about operator overloading, rather how to implement some random logic of selection which arithmetic operator to use in some computation.
Here's a simple function that uses the rand() function to generate a number between low and high, inclusive:
Read about rand(), srand(), and the switch statement.Code:int randomNumber(int low, int high)
{
int range = high - low + 1;
int result = low + rand % range;
return result;
}
Regards,
Zachm
What do you mean by random operator?
Is it an operator that's "fuzzy" so that for example 1+1 will be 2 with high probability but also could be 0 or 3 with a lower probability?
Or do you just want to generate numbers in a range like throwing a die and get 1, 2, 3, 4, 5 or 6 with equal probability 1/6?
Quite possible. But the word "operator" has a specific meaning in C++. Section 5 (Expressions) of the ISO specification provides the definition of what qualifiers as an "operator".
I would have to agree with the Wiz. You are confusing the term "operator" with something else. Section 5 (Expressions) of the ISO specification strictly forbids operating on data types with "user-defined operators".
Yes, that is how I interpreted the question (or if not an arithmetic operation, then one of the characters '+', '-', '/' or '*', chosen at random). In retrospect, _uj's question is worth repeating: what do you mean by random operator?Quote:
Originally Posted by Zachm
Try something like this (if i understood what you wanted correctly that is)
Code:double randOper(double a, double b)
{
switch(rand()%4)
{
case 0:
return a+b;
case 1:
return a-b;
case 2:
return a*b;
case 3:
return a/b; // Div by zero?
}
}