double finalScore(double midterm, double exam) {
// result1 and result2 local variables
double result1 = 0.5*midterm + 0.5*exam;
double result2 = 0.4*midterm + 0.6*exam;
// the final score is the max of result1 and result2
if(result1 >= result2)
return result1;
else
return result2;
}
|
main is a (special) function. All variables
declared there are "local to main".main with the same name?
#include<iostream>
using namespace std;
void f();
void main() {
int x;
x = 5;
f();
cout << "In main, x is " << x << ".\n";
char line[100];
cin.getline(line,100);
}
void f() {
int x = 2;
cout << "In f, x is " << x << ".\n";
}
|
In f, x is 2. In main, x is 5. |
x in the program, the
x in main is different from the
x in the function f.f (resp main) is local
to f (resp main).
#include<iostream> using namespace std; void f();
void f() {
int x = 2;
cout << "In f, x is " << x << ".\n";
}
|
#include<iostream>
using namespace std;
void f();
void main() {
int x;
x = 5;
f();
cout << "In main, x is " << x << ".\n";
char line[100];
cin.getline(line,100);
}
|
#include<iostream>
using namespace std;
void main() {
const double TAX_RATE = 0.25;
double income;
cout << "Please enter your income in year 2001: ";
cin >> income;
cout << "Your tax is " << income*TAX_RATE << ".\n";
char line[100];
cin.getline(line,100);
cin.getline(line,100);
}
|
Please enter your income in year 2001: 33259 Your tax is 8314.75. |
const type variableName =
value; |
#include<iostream>
using namespace std;
void main() {
const double TAX_RATE = 0.25;
TAX_RATE = 0.33; // error!!!! You can't reassign value to a constant
char line[100];
cin.getline(line,100);
}
|
#include<iostream> #include<cmath> using namespace std; |
Enter a radius (in inches): 2 Radius = 2 inches Area of circle = 12.5664 square inches Volume of sphere = 33.5103 cubic inches |
main) are called global
variablesmain.for
statements so that the variable is both declared and initialized
at the start of the statments. example
for(int n = 0; n <= 10; n++) sum = sum + n;The variable
n is local to the body of loop.
#include<iostream>
using namespace std;
void increase(int);
void main() {
int x = 1;
cout << "Before calling the increase function, x is " << x << ".\n";
increase(x);
cout << "After calling the increase function, x is " << x << ".\n";
char line[100];
cin.getline(line,100);
}
void increase(int x) {
x++;
}
|
Before calling the increase function, x is 1. After calling the increase function, x is 1. |