C++ Primer第二章习题(一)

习题2.1

/*
各种类型在本机所在字长 
*/ 
#include<iostream>
int main(){
	std::cout<<"sizeof(int)="<<sizeof(int)<<std::endl;
	std::cout<<"sizeof(long)="<<sizeof(long)<<std::endl;
	std::cout<<"sizeof(long long)="<<sizeof(long long)<<std::endl;
	std::cout<<"sizeof(short)="<<sizeof(short)<<std::endl;
	std::cout<<"sizeof(float)="<<sizeof(float)<<std::endl;
	std::cout<<"sizeof(double)="<<sizeof(double)<<std::endl;
	return 0;
}
//无符号和有符号区别 :unsigned char 0~255;signed char -128~127 

 

习题2.2

利率 float   本金float  付款 double

 

习题2.3 

/*
涉及无符号数的运算 
*/ 
#include<iostream>
int main(){
	unsigned u=10,u2=42;       
	std::cout<<u2-u<<std::endl;           // 32   
	std::cout<<u-u2<<std::endl;          //2^32-32          
	int i=10,i2=42;
	std::cout<<i2-i<<std::endl;           // 32   
	std::cout<<i-i2<<std::endl;           // -32   
	std::cout<<i-u<<std::endl;           // 0   
	std::cout<<u-i<<std::endl;           // 0   
	return 0; 
} 

 

习题2.5

/*
八进制初探 
*/
#include<iostream>
int main(){
	int month=9,day=7;
	std::cout<<month<<day<<std::endl;
//	int month=09,day=07;//八进制没9  故出错 
//	std::cout<<month<<day<<std::endl;
	month=0x9,day=0x7;
	std::cout<<month<<day<<std::endl;
	return 0;
} 

 

习题2.8

/*
转义字符使用 
*/
#include<iostream>
int main(){
	std::cout<<"2M"<<std::endl;
	std::cout<<"2\tM"<<std::endl;
	return 0;
} 

 

习题2.10

/*
变量初始化 
*/
#include<iostream>
std::string global_str;
int global_int;
int main(){
	std::string local_str;
	int local_int;
	std::cout<<"global_str="<<global_str<<std::endl;// empty
	std::cout<<"global_int="<<global_int<<std::endl;// 0
	std::cout<<"local_str="<<local_str<<std::endl;//empty
	std::cout<<"local_int="<<local_int<<std::endl;//未定义 
	return 0;
} 

 

习题2.11

指出下列语句是定义还是声明
(1)extern int  ix=1024;//定义
(2)int iy;//定义
(3)extern int iz;//声明

  

习题2.13

/*
j值多少? 
*/ 
#include<iostream>
int i=42; 
int main(){
	int i=100;
	int j=i;
	std::cout<<j<<std::endl;//100
	return 0;
} 

 

习题2.14

/*
程序输出结果 ? 
*/ 
#include<iostream>
int main(){
	int i=100,sum=0;
	for(int i=0;i!=10;++i)
	sum+=i;
	std::cout<<i<<" "<<sum<<std::endl;//100 45
	return 0;
} 

 

习题2.16

/*
哪些赋值合法? 
*/ 
#include<iostream>
int main(){
	int i=0,&r1=i;
	double d=2.0,&r2=d;
//	r2=3.14159;//合法
/*	r2=r1; 
	std::cout<<r1<<" "<<i<<" "<<r2<<" "<<d<<std::endl;*/
/*	r1=r2; 
	std::cout<<r1<<" "<<i<<" "<<r2<<" "<<d<<std::endl;*/
/*	i=r2;
	std::cout<<r1<<" "<<i<<" "<<r2<<" "<<d<<std::endl;*/
	r1=d;
	std::cout<<r1<<" "<<i<<" "<<r2<<" "<<d<<std::endl;
	return 0; 
} //都能运行 

 

习题2.17

/*
程序输出结果 ? 
*/ 
#include<iostream>
int main(){
	int i,&ri=i;
	i=5;
	ri=10;
	std::cout<<i<<" "<<ri<<std::endl;
	return 0;
} 

 

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。