C++ Primer 中文第 5 版练习答案 第 1 章 开始

自己写的解答,如有错误之处,烦请在评论区指正!


#include <iostream>
int main() {
    std::cout << "Hello, World" << std::endl;
    return 0;
}
#include <iostream>
int main() {
    int v1, v2;
    std::cin >> v1 >> v2;
    std::cout << "The product of " << v1 << " and " << v2
              << " is " << v1 * v2 << std::endl;
    return 0;
}
#include <iostream>
int main() {
    int v1, v2;
    std::cin >> v1 >> v2;
    std::cout << "The product of ";
    std::cout << v1;
    std::cout << " and ";
    std::cout << v2;
    std::cout << " is ";
    std::cout << v1 * v2;
    std::cout << std::endl;
    return 0;
}
  1. 不合法。后两个语句中输出运算符<<左侧没有操作数。后两个语句的前面加上std::cout,或者去掉前两个语句的分号。

  2. 第三句std::cout << /* "*/" */;不合法,其余合法。

#include <iostream>
int main() {
    int sum = 0, val = 50;
    while (val <= 100) {
        sum += val;
        ++val;
    }
    std::cout << "Sum of 50 to 100 inclusive is "
              << sum << std::endl; 
    return 0;
}
#include <iostream>
int main() {
    int val = 10;
    while (val >= 0) {
        std::cout << val << std::endl; 
        --val;
    }
    return 0;
}
#include <iostream>
int main() {
    int begin, end;
    std::cout << "Input two integers (the smaller one first): "
              << std::endl;
    std::cin >> begin >> end;
    while (begin <= end) {
        std::cout << begin << std::endl; 
        ++begin;
    }
    return 0;
}
  1. 计算 -100 到 100 的和。sum终值是 0 。

  2. for:写法简洁,循环次数相对固定;
    while:适用于循环次数不确定的情况。

  3. 书 P13。

  4. (勘误?应该是改写练习 1.11)

#include <iostream>
int main() {
    int begin, end;
    std::cout << "Input two integers: "
              << std::endl;
    std::cin >> begin >> end;
    if (begin > end) {
        int temp = begin;
        begin = end;
        end = temp;
    } 
    while (begin <= end) {
        std::cout << begin << std::endl; 
        ++begin;
    }
    return 0;
}
  1. 书 P18

  2. 书 P19

#include <iostream>
#include "Sales_item.h" 
int main() {
    Sales_item item, sum;
    std::cin >> sum;
    while (std::cin >> item)
        sum += item;
    std::cout << sum << std::endl;
    return 0;
}
#include <iostream>
#include "Sales_item.h"
int main() {
    Sales_item item, sum;
    std::cin >> sum;
    while (std::cin >> item) {
        if (item.isbn() == sum.isbn()) {
            sum += item;
        } else {
            std::cout << sum << std::endl;
            sum = item;
        } 
    }
    std::cout << sum << std::endl;
    return 0;
}

原文链接: https://www.cnblogs.com/gorge/p/12677258.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ Primer 中文第 5 版练习答案 第 1 章 开始

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/340265

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午12:30
下一篇 2023年3月2日 上午12:31

相关推荐