C++ 基础知识回顾

男娘i 2022-07-11 05:32 432阅读 0赞

一、每种数据类型所占内存大小

  1. \#include<iostream>
  2. using namespace std;
  3. int main()
  4. \{
  5. //测试每种数据类型在内存中所占的字节
  6. int a=1;
  7. float b=0.89;
  8. char s\[\]="Hello";
  9. int e=sizeof(s);
  10. cout<<"s\[0\]="<<s\[0\]<<endl;
  11. cout<<"s\[5\]="<<s\[5\]<<endl;
  12. cout<<"int:"<<sizeof(a)<<endl;
  13. cout<<"float:"<<sizeof(b)<<endl;
  14. cout<<"unsigned char:"<<sizeof(unsigned char)<<endl;
  15. cout<<"double:"<<sizeof(double)<<endl;
  16. cout<<"e="<<e<<endl;
  17. \}

运行结果:

Center

二、参数类型之间的转换:

相关函数:atof、atoi、 itoa

表头文件为#include

atof:将字符串转换为浮点数

atoi:将字符串转化为整型数字

itoa:将整型转换为字符串

#include
using namespace std;

#include

int main()

{

  1. const char str\[\]="-3.1415";
  2. float f=atof(str);
  3. int i=atoi(str);
  4. cout<<"f="<<f<<endl;
  5. cout<<sizeof(str)<<endl;
  6. cout<<"i="<<i<<endl;
  7. cout<<"下面将整型转化为字符串"<<endl;
  8. int num=4;
  9. char itostr\[4\];
  10. itoa(num,itostr,2);//10表示转换基础,10表示10进制,2表示二进制
  11. cout<<"itostr="<<itostr<<endl;

}

输出结果:

Center 1

三、swap算法实现:

(1)使用中间变量:

  1. int a=3,b=2;
  2. int temp;
  3. temp=a;
  4. a=b;
  5. b=temp;
  6. cout<<"b="<<b<<endl;
  7. cout<<"a="<<a<<endl;

(2)不使用中间变量的情况:

  1. int a=3,b=2;
  2. a=a+b;
  3. b=a-b;
  4. a=a-b;
  5. cout<<"b="<<b<<endl;
  6. cout<<"a="<<a<<endl;

运行结果都为:

Center 2

(3)使用指针或者引用实现swap算法:

  1. swap.cpp:
  2. #include<iostream>
  3. using namespace std;
  4. //使用指针
  5. void swap1(int *p1,int *p2)
  6. {
  7. int tmp;
  8. tmp=*p1;
  9. *p1=*p2;
  10. *p2=tmp;
  11. }
  12. //使用引用
  13. void swap2(int &a,int &b)
  14. {
  15. int tmp;
  16. tmp=a;
  17. a=b;
  18. b=tmp;
  19. }

main.cpp

  1. #include<iostream>
  2. using namespace std;
  3. extern void swap1(int *p1,int *p2);
  4. extern void swap2(int &a,int &b);
  5. int main()
  6. {
  7. void swap1(int *,int *);
  8. void swap2(int &,int &);
  9. int i1=3,j1=5;
  10. int i2=2,j2=4;
  11. swap1(&i1,&j1);
  12. swap2(i2,j2);
  13. cout<<"交换后i1="<<i1<<endl;
  14. cout<<"交换后j1="<<j1<<endl;
  15. cout<<"交换后i2="<<i2<<endl;
  16. cout<<"交换后j2="<<j2<<endl;
  17. }

运行结果:

  1. ![Center 3][]

发表评论

表情:
评论列表 (有 0 条评论,432人围观)

还没有评论,来说两句吧...

相关阅读

    相关 HTML5基础知识回顾

    > 趁青春没有理由不去闯,即使会败,我也要败得漂亮!人生在世,不妨大胆一点,勇敢地去追逐自己想要的东西!加油,勇敢点,你是最棒的!我是梦阳辰,期待与你相遇! 文章目录