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

C++ Primer 中文版(第 5 版)练习解答合集

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


#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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值