#include <iostream> using namespace std; int main() { //Constants for minimum income and years const double MIN_INCOME = 35000.0; const int MIN_YEARS = 5; // Get the annual income cout << "What is your annual income? "; double income; // Variable definition cin >> income; if (income >= MIN_INCOME) { //Income is high enough, so get years at current job cout << "How many years have you worked at your current job? "; int years; // Variable defined inside the if block cin >> years; if (years > MIN_YEARS) cout << "nYou qualify.n"; else cout << "nYou must have been employed for more than "<< MIN_YEARS << " years to qualify.n"; } else // Income is too low { cout << "nYou must earn at least $" << MIN_INCOME << " to qualify.n"; } return 0; }程式的第 11 行中定義了 income 變數,它在標記 main 函數程式碼塊的大括號內,所以它的作用域包括第 11?28 行,也就是從它被定義的行到 main 函數封閉大括號的位置,在這個作用域內它都可以被程式使用。
// This program uses two variables with the same name. #include <iostream> using namespace std; int main() { int number; // Define a variable named number cout << "Enter a number greater than 0: "; cin >> number; if (number > 0) { int number; // Define another variable named number cout << "Now enter another number: "; cin >> number; cout << "The second number you entered was "; cout << number << endl; } cout << "Your first number was " << number << endl; return 0; }程式輸出結果:
Enter a number greater than 0: 2
Now enter another number: 7
The second number you entered was 7
Your first number was 2