8 //and maximum number of peas in a pod.9 int main( )10 {This variable named11 int maxCount, minCount, podCount;averagePea is local to the12 double averagePea, yield;main function.13 cout << "Enter minimum and maximum number of peas in a pod: ";14 cin >> minCount >> maxCount;15 cout << "Enter the number of pods: ";16 cin >> podCount;17 cout << "Enter the weight of an average pea (in ounces): ";18 cin >> averagePea;19 yield =20 estimateOfTotal(minCount, maxCount, podCount) * averagePea;21 cout.setf(ios::fixed);22 cout.setf(ios::showpoint);23 cout.precision(3);24 cout << "Min number of peas per pod = " << minCount << endl25 << "Max number of peas per pod = " << maxCount << endl26 << "Pod count = " << podCount << endl27 << "Average pea weight = "28 << averagePea << " ounces" << endl29 << "Estimated average yield = " << yield << " ounces"30 << endl;31 return 0;32 }3334 double estimateOfTotal(int minPeas, int maxPeas, int podCount)35 {36 double averagePea;averagePea is local tothe function estimateOfTotal.37 averagePea = (maxPeas + minPeas)/2.0;38 return (podCount * averagePea);39 }
Scope Rules 119
Display 3.8 Local Variables (part 2 of 2)SAMPLE DIALOGUEEnter minimum and maximum number of peas in a pod: 4 6Enter the number of pods: 10Enter the weight of an average pea (in ounces): 0.5Min number of peas per pod = 4 Max number of peas per pod = 6Pod count = 10 Average pea weight = 0.500 ouncesEstimated average yield = 25.000 ouncesWhen the variable
averagePea is given a value in the function call to
estimateOfTotal,
this does not change the value of the variable in the
main function that is also named
averagePea.
Variables that are declared within the body of a function definition are said to be
local variablelocal to that function or to have that function as their scope. If a variable is local tosome function, we sometimes simply call it a local variable, without specifying the
scopefunction.
Another example of local variables can be seen in Display 3.5. The definition of the
function
totalCost in that program begins as follows:
double totalCost(int numberParameter, double priceParameter){ const double TAXRATE = 0.05; //5% sales tax double subtotal;The variable
subtotal is local to the function
totalCost. The named constant
TAXRATEis also local to the function
totalCost. (A named constant is in fact nothing but a vari-
able that is initialized to a value and that cannot have that value changed.)
L
OCAL V
ARIABLESVariables that are declared within the body of a function definition are said to be local to that functionor to have that function as their scope.
If a variable is local to a function, then you can have another variable (or other kind of item) with the same name that is declared in another func-tion definition; these will be two different variables, even though they have the same name. (In particular, this is true even if one of the functions is the main function.)
Bạn đang xem 8 / - ABSOLUTE C PHẦN 3 PPS