C++ Primer 第五章答案

练习5.1
空语句是无内容的语句,在我们不需要语句但是语法要求的时候
while(等待信号);//等待信号到了之后再执行之后的程序。

练习5.2
块:用花括号括起来的语句和声明的序列。
在程序的某个地方,语法需要一条语句,但是逻辑需要多条语句时。

练习5.3
#include <iostream>
int main()
{
    int sum = 0, val = 1;
    while (val <= 10)
        sum += val, ++val;
    std::cout << "Sum of 1 to 10 inclusive is "
              << sum << std::endl;

    return 0;
}
可读性是变低了。

练习5.4
(a)iter是未初始化的
(b)status存在于while语句块中,if中的status将是未定义的
bool status;
while ((status = find(word))) {/* ... */}
if (!status) {/* ... */})

练习5.5
 #include <iostream>

using namespace std;

int main()
{
    int grade = 0;
    cout << "please input a grade" << endl;
    cin >> grade;
    if (grade > 85)
    {
        cout << "A" << endl;
    }
    else if (grade > 60)
    {
        cout << "B" << endl;
    }
    else
    {
        cout << "C" << endl;
    }
    system("pause");
    return 0;
}

练习5.6
#include <iostream>

using namespace std;

int main()
{
    int grade = 0;
    cout << "please input a grade" << endl;
    cin >> grade;

    string commend;
    commend = (grade > 85) ? "A" : (grade > 60) ? "B" : "C";
    cout << commend << endl;

    system("pause");
    return 0;
}

练习5.7
(a) 
if (ival1 != ival2) ival1 = ival2; //分号
    else ival1 = ival2 = 0;
(b)
 if (ival < minval)//不加花括号,ocurs = 1;总会被执行
    {
        minval = ival;
        occurs = 1;
    }
(c)
 int val;//定义在第一个if里,第二个if将是未定义的
    if (ival = get_value())
        cout << "ival = " << ival << endl;
    if (!ival) 
        cout << "ival = 0\n";
(d)
    if (ival == 0)// = 是赋值
        ival = get_value();

练习5.8
在程序中if多余else,C++匹配最近的if和else

练习5.9 -12

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值