c++学习笔记——复合语句()

#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;
20
100
20

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值