当前位置:嗨网首页>书籍在线阅读

25-复习题

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

6.10 复习题

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

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

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

2.在程序清单6.2中,用ch+1替换++ch将发生什么情况呢?

3.请认真考虑下面的程序:

#include <iostream>
using namespace std;
int main()
{
    char ch;
    int ct1, ct2;
    ct1 = ct2 = 0;
    while ((ch = cin.get()) != '$')
    {
        cout << ch;
        ct1++;
        if (ch = '$')
            ct2++;
        cout << ch;
    }
    cout <<"ct1 = " << ct1 << ", ct2 = " << ct2 << "\n";
    return 0;
}

假设输入如下(请在每行末尾按回车键):

Hi!
Send $10 or $20 now!

则输出将是什么(还记得吗,输入被缓冲)?

4.创建表示下述条件的逻辑表达式:

a.weight大于或等于115,但小于125。

b.ch为q或Q。

c.x为偶数,但不是26。

d.x为偶数,但不是26的倍数。

e.donation为1000-2000或guest为1。

f.ch是小写字母或大写字母(假设小写字母是依次编码的,大写字母也是依次编码的,但在大小写字母间编码不是连续的)。

5.在英语中,“I will not not speak(我不会不说)”的意思与“I will speak(我要说)”相同。在C++中,!!x是否与x相同呢?

6.创建一个条件表达式,其值为变量的绝对值。也是说,如果变量x为正,则表达式的值为x;但如果x为负,则表达式的值为−x——这是一个正值。

7.用switch改写下面的代码片段:

if (ch == 'A')
    a_grade++;
else if (ch == 'B')
    b_grade++;
else if (ch == 'C')
    c_grade++;
else if (ch == 'D')
    d_grade++;
else
    f_grade++;

8.对于程序清单6.10,与使用数字相比,使用字符(如a和c)表示菜单选项和case标签有何优点呢?(提示:想想用户输入q和输入5的情况。)

9.请看下面的代码片段:

int line = 0;
char ch;
while (cin.get(ch))
{
    if (ch == 'Q')
           break;
    if (ch != '\n')
           continue;
    line++;
}

请重写该代码片段,不要使用break和continue语句。