C++ 基础知识回顾

本文介绍了C++中各种数据类型的内存占用情况,并演示了如何使用atof、atoi及itoa进行不同数据类型间的转换。此外,还提供了两种实现swap算法的方法,包括使用中间变量和不使用中间变量的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

      #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<stdlib.h>

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

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

 itoa:将整型转换为字符串

 #include<iostream>
 using namespace std;

 #include<stdlib.h>

 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;
}
运行结果:  

    


 

       

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Linda Fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值