C++ Primer Plus第六章复习题

1、请看下面两个计算空格和换行符数目的代码片段:

//Version 1
while (cin.get(ch))
{
    if(ch == ' ')
        spaces++;
    if(ch == '\n')
        newlines++;
}
//Version 2
while (cin.get(ch))
{
    if(ch == ' ')
        spaces++;
    else if(ch == '\n')
        newlines++;
}

第二种格式比第一种好在哪里呢? 

答:这两个版本将给出相同的答案,但是ifelse效率更高。因为如果第一个判断成立的话。第二种格式不会执行第二个判断,而第一种格式会执行第二个判断。

2、在下图程序中,用ch+1替换++ch将发生什么情况呢?

//ifelse.cpp -- using the if else statement
#include <iostream>
int main()
{
    char ch;
    std::cout <<"Typt,and I shall repeat.\n";
    std::cin.get(ch);
    while(ch != '.')
    {
        if(ch == '\n')
            std::cout << ch;
        else
            std::cout << ++ch;
        std::cin.get(ch);
    }
    std::cout << "\nPlease excuse the slight confusion.\n";
    return 0;
}

 答:++ch 和ch+1得到的数值相同。但++ch的类型为char,将作为字符打印,而ch+1是int类型(因为char和1相加),将作为

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值