C++ 基础知识回顾
一、每种数据类型所占内存大小
\#include<iostream>
using namespace std;
int main()
\{
//测试每种数据类型在内存中所占的字节
int a=1;
float b=0.89;
char s\[\]="Hello";
int e=sizeof(s);
cout<<"s\[0\]="<<s\[0\]<<endl;
cout<<"s\[5\]="<<s\[5\]<<endl;
cout<<"int:"<<sizeof(a)<<endl;
cout<<"float:"<<sizeof(b)<<endl;
cout<<"unsigned char:"<<sizeof(unsigned char)<<endl;
cout<<"double:"<<sizeof(double)<<endl;
cout<<"e="<<e<<endl;
\}
运行结果:
二、参数类型之间的转换:
相关函数:atof、atoi、 itoa
表头文件为#include
atof:将字符串转换为浮点数
atoi:将字符串转化为整型数字
itoa:将整型转换为字符串
#include
using namespace std;
#include
int main()
{
const char str\[\]="-3.1415";
float f=atof(str);
int i=atoi(str);
cout<<"f="<<f<<endl;
cout<<sizeof(str)<<endl;
cout<<"i="<<i<<endl;
cout<<"下面将整型转化为字符串"<<endl;
int num=4;
char itostr\[4\];
itoa(num,itostr,2);//10表示转换基础,10表示10进制,2表示二进制
cout<<"itostr="<<itostr<<endl;
}
输出结果:
三、swap算法实现:
(1)使用中间变量:
int a=3,b=2;
int temp;
temp=a;
a=b;
b=temp;
cout<<"b="<<b<<endl;
cout<<"a="<<a<<endl;
(2)不使用中间变量的情况:
int a=3,b=2;
a=a+b;
b=a-b;
a=a-b;
cout<<"b="<<b<<endl;
cout<<"a="<<a<<endl;
运行结果都为:
(3)使用指针或者引用实现swap算法:
swap.cpp:
#include<iostream>
using namespace std;
//使用指针
void swap1(int *p1,int *p2)
{
int tmp;
tmp=*p1;
*p1=*p2;
*p2=tmp;
}
//使用引用
void swap2(int &a,int &b)
{
int tmp;
tmp=a;
a=b;
b=tmp;
}
main.cpp
#include<iostream>
using namespace std;
extern void swap1(int *p1,int *p2);
extern void swap2(int &a,int &b);
int main()
{
void swap1(int *,int *);
void swap2(int &,int &);
int i1=3,j1=5;
int i2=2,j2=4;
swap1(&i1,&j1);
swap2(i2,j2);
cout<<"交换后i1="<<i1<<endl;
cout<<"交换后j1="<<j1<<endl;
cout<<"交换后i2="<<i2<<endl;
cout<<"交换后j2="<<j2<<endl;
}
运行结果:
![Center 3][]
还没有评论,来说两句吧...