C++ Primer 第五章答案

本文档提供了C++ Primer第五章多个练习题的答案,包括空语句的作用、代码块的使用、循环与条件语句的实践,以及如何处理变量初始化、流程控制和错误处理等问题。示例代码展示了如何计算1到10的和、读取输入并根据成绩输出等级,以及处理字符计数等任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习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
#include <iostream>

using namespace std;

int main()
{
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, SpaceCnt = 0, newLineCnt = 0, ffCnt = 0, flCnt = 0, fiCnt = 0;
    char ch;
    char f_ch = '\0';

    while (cin >> ch) {
        if (ch == 'a'|| ch == 'A')
            ++aCnt;
        else if (ch == 'e'|| ch == 'E')
            ++eCnt;
        else if (ch == 'i' || ch == 'I')
        {
            ++iCnt;
            if (f_ch == 'f')
            {
                fiCnt++;
            }
        }
            
        else if (ch == 'o' || ch == 'O')
            ++oCnt;
        else if (ch == 'u' || ch == 'U')
            ++uCnt;
        else if (ch == ' ')
            ++SpaceCnt;
        else if (ch == '\n')
            ++newLineCnt;
        else if (ch == 'f' && f_ch == 'f')
        {
            ffCnt++;
        }
        else if (ch == 'l' && f_ch == 'f')
        {
            flCnt++;
        }
        f_ch = ch;
    }

    cout << "Number of vowel a: \t" << aCnt << '\n' << "Number of vowel e: \t"
        << eCnt << '\n' << "Number of vowel i: \t" << iCnt << '\n'
        << "Number of vowel o: \t" << oCnt << '\n' << "Number of vowel u: \t"
        << uCnt << "Number of Space: \t" << SpaceCnt << '\n' 
        << "Number of Enter: \t" << newLineCnt << '\n'
        << "Number of ff: \t" << ffCnt << '\n'
        << "Number of fi: \t" <<fiCnt << '\n'
        << "Number of fl: \t" <<flCnt << '\n'
        << endl;

    system("pause");
    return 0;
}

练习5.13
(a) unsigned aCnt = 0, eCnt = 0, iouCnt = 0;
    char ch = next_text();
    switch (ch) {
        case 'a': aCnt++;break;
        case 'e': eCnt++;break;
        default: iouCnt++;break;
    }
(b) unsigned index = some_value();
    int ix;
    switch (index) {
        case 1:
            int ix = get_value();
            ivec[ ix ] = index;
            break;
        default:
            ix = ivec.size()-1;
            ivec[ ix ] = index;
    }
(c) unsigned evenCnt = 0, oddCnt = 0;
    int digit = get_num() % 10;
    switch (digit) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 9:
            oddcnt++;
            break;
        case 2:
        case 4:
        case 6:
        case 8:
        case 0:
            evencnt++;
            break;
    }
(d)
 unsigned ival=512, jval=1024, kval=4096;
    unsigned bufsize;
    unsigned swt = get_bufCnt();
    switch(swt) {
        case 512:
            bufsize = ival * sizeof(int);
            break;
        case 1024:
            bufsize = jval * sizeof(int);
            break;
        case 4069:
            bufsize = kval * sizeof(int);
            break;
    }

练习5.14
#include <iostream>
#include <vector>
using namespace std;


int main()
{
    string test = "\0", pretest = "\0", testMax = "\0";
    int cnt = 0, cntMax = 0;
    while (cin >> test)
    {
        if (test == pretest)
        {
            cnt++;
        }
        else
        {
            if (cntMax < cnt)
            {
                cntMax = cnt;
                testMax = pretest;
            }
            pretest = test;
            cnt = 1;
        }
        if(test == "end")
        {
            break;
        }
        
    }
    if (cntMax <= 1)
    {
        cout << "no word was repeated" << endl;
    }
    else 
    {
        cout << "the word '" << testMax << "' occurred " << cntMax << " times" << endl;
    }
    system("pause");
    return 0;
}

练习5.15
int ix;
(a) for ( ix = 0; ix != sz; ++ix) { /* ... */ }
    if (ix != sz)
    // . . .
(b) int ix;
    for ( ;ix != sz; ++ix) { /* ... */ }
(c) for (int ix = 0; ix != sz; ++ix) { /*...*/ }

练习5.16

练习5.17
#include <iostream>
#include <vector>
using namespace std;

bool compare(vector<int> arry1, vector<int> arry2)
{
    vector<int> arryMini, arryMax;
    if (arry1.size() < arry2.size())
    {
        arryMini = arry1;
        arryMax = arry2;
    }
    else
    {
        arryMini = arry2;
        arryMax = arry1;
    }    
    for (auto it = arryMini.begin(); it != arryMini.end(); it++)
    {
        if (*it != *(arryMax.begin() + (it - arryMini.begin())))
        {
            return false;
        }
    }
    return true;
}

int main()
{
    vector<int> arry1 = {0,1,2}, arry2 = { 0,1,2,3,4 };
    bool result = compare(arry1, arry2);
    
    cout << result << endl;
    system("pause");
    return 0;
}

练习5.18
(a) do { // added bracket.//加上花括号
        int v1, v2;
        cout << "Please enter two numbers to sum:" ;
        if (cin >> v1 >> v2)
            cout << "Sum is: " << v1 + v2 << endl;
    }while (cin);
(b) int ival;
    do {
        // . . .
    } while (ival = get_response());
(c) int ival;
    do {
        ival = get_response();
    } while (ival); 

练习5.19
#include <iostream>
using namespace std;

int main()
{
    string s1, s2;
    cout << "please input two string" << endl;
    do
    {
        if (s1.size() < s2.size())
        {
            cout << s1 << endl;
        }
        else
        {
            cout << s2 << endl;
        }
    } while (cin >> s1 >> s2);
    system("pause");
    return 0;
}

练习5.20

练习5.21
#include <iostream>

using namespace std;

int main()
{
    string curr, prev;
    bool no_twice = false;

    while (cin >> curr) {
        if (!isupper(curr[0])) {
            prev = "";
            continue;
        }
        if (prev == curr) {
            cout << curr << " occurs twice in succession." << endl;
            no_twice = true;
            break;
        }
        prev = curr;
    }
    if (!no_twice) cout << "no word was repeated." << endl;
    system("pause");
    return 0;
}

练习5.22
for (int sz = get_size(); sz <=0; sz = get_size());

练习5.23

练习5.24
#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    if (0 == b)
    {
        throw runtime_error("divisor is 0");
    }

    cout << a / b << endl;
    system("pause");
    return 0;
}

练习5.25
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int a, b;
    cout << "Input two integers: ";
    while (cin >> a >> b) {
        try {
            if (b == 0) throw runtime_error("divisor is 0");
            cout << a / b << endl;
            cout << "Input two integers: ";
        }
        catch (runtime_error err) {
            cout << err.what();
            cout << "\nTry Again? Enter y or n:" << endl;
            char c;
            cin >> c;
            if (!cin || c == 'n')
                break;
            else
                cout << "Input two integers: ";
        }
    }
    system("pause");
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值