C++Primer第五版——習題答案詳解(一)



習題答案目錄:https://www.cnblogs.com/Mered1th/p/10485695.html

第1章 開始&&第2章 變量和基本類型


練習1.3

#include<iostream>
int main(){
	std::cout<<"Hello world"<<std::endl;
	return 0;
}

練習1.4

#include<iostream>
int main(){
	std::cout << "Input two numbers: " << std::endl;
	int a, b;
	std::cin >> a >> b;
	std::cout << a <<" * "<< b << " = " << a * b << std::endl;
}

練習1.5

#include<iostream>
int main(){
	std::cout << "Input two numbers: " << std::endl;
	int a, b;
	std::cin >> a >> b;
	std::cout << a;
	std::cout<<" * ";
	std::cout<< b ;
	std::cout<< " = " ;
	std::cout<< a * b ;
	std::cout<< std::endl;
}

練習1.6
不合法,第一行有分號表示語句結束,改為如下:

#include<iostream>
int main(){
	std::cout << "Input two numbers: " << std::endl;
	int a, b;
	std::cin >> a >> b;
	std::cout << "The sum of "<< a << " and " << b<< " is " << a + b <<std::endl; 
    return 0;
}

練習1.7

#include<iostream>
int main(){
	/*
	/* */注釋不能嵌套!  
	*/
	return 0;
}

練習1.8
第三行錯誤,因前雙引號被注釋掉了,后雙引號不匹配。

#include<iostream>
int main(){
	std::cout << "/*"<<std::endl;
	std::cout << "*/"<<std::endl;
	//std::cout << /* "*/" */<<std::endl;
	std::cout << /* "*/" /* "/*" */<<std::endl;
	return 0;
}

練習1.9

 #include<iostream>
int main(){
	int sum = 0, val = 50;
	while (val <= 100){
		sum += val;
		++val;
	}
	std::cout << sum << std::endl;
	return 0;
}

練習1.10

#include<iostream>
int main(){
	int sum = 0, val = 10;
	while (val >= 0){
		sum += val;
		--val;
	}
	std::cout << sum << std::endl;
	return 0;
}

練習1.11

#include<iostream>
int main(){
	int a, b;
	std::cin >> a >> b;
	while (a <= b){
		std::cout << a << " ";
		++a;
	}
	return 0;
}

練習1.12
程序的功能是求[-100,100]范圍內的整數的和,sum的終值為0

練習1.14
已知循環次數的時候用for簡便,未知時用while簡便。

練習1.16

#include<iostream>
int main(){
	int a, sum = 0;
	while(std::cin >> a){
		sum += a;
	}
	std::cout << sum;
	return 0;
}

練習1.19

#include<iostream>
int main(){
	int a, b;
	std::cin >> a >> b;
	if( a > b ){
		int temp = a;
		a = b;
		b = temp;
	}
	while (a <= b){
		std::cout << a << " ";
		++a;
	}
	return 0;
}

練習1.20

#include <iostream>
#include "Sales_item.h"
int main(){
	Sales_item book;
	while(std::cin >> book){
		std::cout << "Record: " << book <<std::endl;
	}
	return 0;
}

練習1.21

#include <iostream>
#include "Sales_item.h"
int main(){
	Sales_item book1, book2;
	std::cin >> book1 >> book2;
	std::cout << book1 + book2 <<std::endl;
	return 0;
}

練習2.8

#include<iostream>
int main(){
    cout<<"2M"<<'\n';
    cout<<'2'<<'\t'<<'M'<<'\n';
}

練習2.9
a.需要在cin前定義變量名
b.3.14強制轉換為Int有精度損失
c.wage未定義
d.同b

練習2.15
a.定義合法但有精度損失
b.引用類型的初始值必須是一個對象
c.正確
d.同b

練習2.17
10 10

練習2.27
a.不合法,引用r的賦值對象必須是一個對象
b.合法,將p2設置為一個常量指針,初始化為i2對象的地址
c.合法,將i設為常量-1,r設置為常量的引用
d.合法,將p3設為指向常量的常量指針,初始化為i2的地址
e.合法,將p1設為指向常量的指針,初始化為i2的地址
f.不合法,常量指針必須初始化
g.合法

練習2.28
a.不合法,常量指針必須初始化
b.不合法,同a
c.不合法,常量ic未初始化
d.不合法,同a
e.合法。


不斷學習中,歡迎交流!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM