问题
I have a method drive that goes like this:
public double drive(double milesTraveled, double gasUsed)
{
gasInTank -= gasUsed;
return totalMiles += milesTraveled;
}
I know I can't return multiple values from a method, but that's kind of what I need to do because I need both of these values in my main method, and as it is now it's obviously only returning the one. I can't think of anything that would work. Sorry if this is a super beginner question. What can I do to get both values to return from the method?
回答1:
You can return multiple value from a function. To do this You can use structure.
In the structure you can keep required field and can return structure variable after operation.
You can also make a class for the required field if You are using OOPS supporting language but Structure is best way.
回答2:
In most languages you can only return a single value from a method. That single value could be a complex type, such as a struct, array or object. Some languages also allow you to define output parameters or pass in pointers or references to outside storage locations. These kinds of parameters also allow you to return additional values from your method.
回答3:
not sure, but can you take array of your values?
array[0]=gasInTank;
array[0] -= gasUsed;
array[1]=milesTraveled;
array[1] -= milesTraveled;
return array;
来源:https://stackoverflow.com/questions/15104789/returning-multiple-values-from-a-method