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<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;
}
運行結果:  

    


 

       

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章