#include <iostream>
int main()
{
using namespace std;
cout << "The Amazing Acounto will sum and average ";
cout << "five numbers for you.\n";
cout << "Please enter five values:\n";
double number;
double sum = 0.0;
for (int i = 1; i <= 5; i++)
{
cout << "Value " << i << ": ";
cin >> number;
sum += number;
}
//要在循环体中包含多条语句,方法就是用两个花括号来构造一条复合语句(代码块)
//假设对循环体进行了缩进,但是省略了花括号,编译器将忽略缩进,因此只要第一条语句位于循环
//如果在语句块中定义一个新的变量,则当程序执行个语句块中的语句时,该变量才会存在
//执行完成该语句时,变量将会被释放。
cout << "Five exquisite choices indeed! ";
cout << "They sum to " << sum << endl;
cout << "and average to " << sum/5 << ".\n";
cout << "The Amazing Accounto bids you adieu!\n";
return 0;
}
Please enter five values:
Value 1: 5
Value 2: 5
Value 3: 8
Value 4: 5
Value 5: 5
Five exquisite choices indeed! They sum to 28
and average to 5.6.
The Amazing Accounto bids you adieu!
#include <iostream>
int main()
{
using namespace std;
int x = 20;
{
int y = 100;
cout << x << endl;//在外部定义了的变量在内部语句块中也是被定义了的
cout << y << endl;
}
cout << x << endl;
//cout << y << endl;error
//在语句块中定义一个新变量,只有当程序执行该语句中的语句时,该变量才会存在。
//执行完该语句块时,变量就会表释放。
return 0;
}
20
100
20
#include <iostream>
int main()
{
using std::cout;
using std::endl;
int x = 20;
{
cout << x << endl;//此处输出的是外部定义的x值
int x = 100;
//在外部也定了x(第6行),在声明位置到内部语句块结束的范围内,
//新变量将隐藏旧变量(第9行和第12行输出是100),然后旧变量再次可见(第15行输出是20)
cout << x << endl;
}
cout << x << endl;
return 0;