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;
}
-
不合法。后两个语句中输出运算符
<<
左侧没有操作数。后两个语句的前面加上std::cout
,或者去掉前两个语句的分号。 -
略
-
第三句
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;
}
-
计算 -100 到 100 的和。
sum
终值是 0 。 -
略
-
for
:写法简洁,循环次数相对固定;
while
:适用于循环次数不确定的情况。 -
略
-
书 P13。
-
略
-
略
-
(勘误?应该是改写练习 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;
}
-
书 P18
-
书 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;
}
-
略
-
略