《C++ Primer》练习全解 1.4.2节

练习1.12:下面for循环完成了什么功能?sum的终值是多少?

int sum = 0;
for(int i = -100 ; i <= 100 ; ++i)
    sum += i;

 

循环完成的功能是从-100到100整数相加的和,sum的终值是0

练习1.13:使用for循环重做1.4.1节中的所有练习(第11页)

        1.4.1节中的所有练习

                        练习1.9:编写程序,使用while循环将50到100的整数相加。

                        我们用for。

#include<iostream>
using namespace std;
int main()
{
    int sum = 0;
    for (int i = 50; i <= 100; ++i)
        sum += i;
    cout << sum << endl;
}

 

                        

                        练习1.10:除了++运算符将运算对象的值增加1之外,还有一个递减运算符(-)实现将值减少1。编写程序,使用递减运算符在循环中按递减顺序打印出10到0之间的整数。

#include<iostream>
using namespace std;
int main()
{
    for (int i = 10; i >= 1; --i)
        cout << i << endl;
}

 

                        练习1.11 编写程序,提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数。

#include<iostream>
using namespace std;
int main()
{
    cout << "请输入两个整数:";
    int a, b;
    cin >> a >> b;
    if (a > b)
    {
        for (; b <= a; b++)
        {
            cout << b<<endl;
        }
        return 0;
    }
    if (b > a)
    {
        for (; a <= b; a++)
        {
            cout << a<<endl;
        }
        return 0;
    }
}

 

练习1.14 对比for循环和while循环,两种形式的优缺点各是什么?

参考pezy:

  • Advantage of   for and disadvantage of while:
    • Locality, the variable in the scope of the loop.
    • Pattern happens so often: using a variable in a condition and incrementing that variable in the body.
  • Advantage of while and disadvantage of for:
    • Clear when there is only one static condition.
    • Readable when the global variables incremented in the body.

简单来说,for的优点是:变量能在范围内循环。循环模式经常能够刷新,一个变量一个循环条件。

while的优点是:当只有一个静态条件时,这个条件比较清晰。当全局变量在递增时,可读性比较强。

练习1.15编写程序,包含第14页“再探编译”中讨论的常见错误。熟悉编译器生成的错误信息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Evonso

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值