Well, the problem is a function can only return one value. It is possible though to return multiple values by passing parameters as references or through pointers.
Now, as you said, function1 works as a database or rather repository of data. You want to extract different values from it with different calls. The point is that you need to specify the function what kind of values you need for it.
You have 2 values/coefficients: one for armor and one for swords. You need to tell the function which of the two you need. So, you can do something like this:
Then you can use it like this:Code:enum Item { Armor, Sword }; int GetCoefficient(Item item) { int value = 0; switch(item) { case Armor: value = 25; break; case Sword: value = 15; break; } return value; }
Of course, you can simplify all that by using a std::map. This is a class that associates a value to a key. The key (used to identify the value) is the item type, and the value is the coefficient.Code:int sword = 15; int armor = 10; sword = sword *GetCoefficient(Sword); armor = armor *GetCoefficient(Armor);
Of course, you can make the coefficients variable global, or local to a function or member of a class (though that is probably too advance for you now).Code:#include <map> #include <cstdio> #include <cstdlib> #include <iostream> using namespace std; enum Item { Armor, Sword }; int main(int nNumberofArgs, char* pszArgs[]) { int sword = 15; int armor = 10; std::map<Item, int> coefficients; coefficients[Armor] = 25; coefficients[Sword] = 15; sword = sword * coefficients[Armor]; armor = armor * coefficients[Sword]; //behind armor, here cout <<"The sword value is: "<<sword<<endl; cout <<"The armor value is: "<<armor<<endl; system ("PAUSE"); return 0; }




Marius Bancila
Reply With Quote