前六章已经学过一次了,就只再写一次习题。
1.1
int main() {
return 0;
}
1.2
int main() {
return -1;
}
1.3
int main() {
std::cout << "Hello world";
return 0;
}
1.4
int main() {
int i = 4, x = 5;
std::cout << "i+x=" << i + x;
std::cout << "i*x=" << i * x;
return 0;
}
1.5
int main() {
int i = 4, x = 5;
std::cout << "i+x=" << i + x << "i*x=" << i * x;
return 0;
}
1.6
不合法,因为输出运算符间用分号隔开了,将分号去掉即可。
1.7
嵌套注释如下错误
1.8
第1,2,4个合法
注:ctrl+k然后ctrl+c快速注释
1.9
int main() {
int sum = 0;
int i = 50;
while (i<=100) {
sum += i;
i++;
}
std::cout << sum;
return 0;
}
1.10
int main() {
int i = 10;
while (i >= 0) {
std::cout << i << std::endl;
--i;
}
return 0;
}
1.11
int main() {
int v1, v2,v3= 0;
std::cout << "Enter two numbers"<<std::endl;
std::cin >> v1 >> v2;
if (v1 < v2) { v3 = v2;
v2 = v1;
v1 = v3;
}
while (v1 >= v2) {
std::cout << v1<<std::endl;
--v1;
}
return 0;
}
1.12
完成了-100到100的整数相加
sum=0
1.13
int main() {
int sum = 0;
int i = 50;
for(i=50;i<=100;i++){
sum+=i ;
}
std::cout << sum;
return 0;
}
int main() {
int i = 10;
for(i=10;i>=0;--i){
std::cout<<i;
}
int main() {
int v1, v2,v3= 0;
std::cout << "Enter two numbers"<<std::endl;
std::cin >> v1 >> v2;
if (v1 < v2) { v3 = v2;
v2 = v1;
v1 = v3;
}
for(;v1>=v2;--v1){
std::cout << v1<<std::endl;
}
return 0;
}
1.14
for比较简洁
while比较适用于循环次数不易预知的情况
在功能上是等价的,可以相互转换。
1.15
语法错误
类型错误
声明错误(初始化)
1.16
int main() {
int v1= 0;
int v2 = 0;
while (std::cin >> v1) {
v2 += v1;
}
std::cout << v2;
return 0;
}
1.17 1.18
int main() {
int v1= 0;
int v2 = 0;
int cnt = 1;
if (std::cin >> v1) {
while (std::cin >> v2) {
if (v1 == v2) cnt++;
else { std::cout << v1 << "occurs" << cnt << "times"<<std::endl;
cnt = 1;
v1 = v2;
}
}std::cout << v1 << "occurs" << cnt << "times" << std::endl;
}
return 0;
}
都会输出相应的结果
1.19
原程序已经考虑了这种情况
1.20
int main() {
Sales_item item;
while (std::cin >> item)
std::cout << item;
return 0;
}
1.21
int main()
{
Sales_item item1,item2;
while (std::cin>>item1>>item2)
std::cout << item1+item2;
return 0;
}
1.22
int main()
{
Sales_item item1,item2;
std::cin>>item1;
while (std::cin>>item2)
item1+=item2;
std::cout<<item1;
return 0;
}
1.23 1.24
int main() {
Sales_item item1, item2;
int v1 = 0;
int v2 = 0;
int cnt = 1;
if (std::cin >> item1) {
while (std::cin >> item2) {
if (item1.isbn() == item2.isbn()) cnt++;
else {
std::cout << item1.isbn() << "occurs" << cnt << "times" << std::endl;
cnt = 1;
item1.isbn() = item2.isbn();
}
}std::cout << item1.isbn() << "occurs" << cnt << "times" << std::endl;
}
return 0;
}
1.25
int main()
{
Sales_item totalBook;//统计对象
if(std::cin>>totalBook){//第一次读取的值赋值给totalBook
Sales_item currBook;//当前对象
while(std::cin>>currBook)//从第二次开始,读取的值赋给currBook
{
if(totalBook.isbn()==currBook.isbn())//上一次读取的对象与当前读取的对象书本编号相等,就叠加
{
totalBook += currBook;
}else{//否则就打印上次书本统计的结果,接着又把当前读取的对象赋值给统计对象
std::cout<<totalBook<<std::endl;
totalBook = currBook;
}
}
std::cout<<totalBook<<std::endl;//打印最后统计的值
}else{
std::cerr<<"no data!!!"<<std::endl;
return -1;
}
return 0;
}