2008年2月1日

C++中几种不同交换两个数的方法

#include<iostream>
using namespace std;
void swapr(int & a, int &b);
void swapp( int * a, int * b);
void swapv(int a,int b);

int main()
{
    
int a,b;

    cout
<<"请输入a"<<endl;
    cin
>>a;
    cout
<<"请输入b"<<endl;
    cin
>>b;

    cout
<<"交换前"<<endl;
    cout
<<"a = "<<a<<endl;
    cout
<<"b = "<<b<<endl;

    cout
<<"使用引用交换"<<endl;
    swapr(a,b);
    cout
<<"a = "<<a<<endl;
    cout
<<"b = "<<b<<endl;


    cout
<<"使用指针交换"<<endl;
    swapp(
&a,&b);
    cout
<<"a = "<<a<<endl;
    cout
<<"b = "<<b<<endl;

    cout
<<"使用值交换"<<endl;
    swapv(a,b);
    cout
<<"a = "<<a<<endl;
    cout
<<"b = "<<b<<endl;





    
return 0;
}





    
void swapr(int & a, int &b)
    
{
        
int temp;
        temp 
= a;
        a 
= b;
        b 
= temp;
    }

 

    
void swapp( int * a, int * b)
    
{
        
int temp;
        temp 
= *a;
        
*= *b;
        
*= temp;
    }


    
void swapv(int a,int b)
    
{
        
int temp;
        temp 
= a;
        a 
= b;
        b 
= temp;
    }
我们可以发现使用值传递并不能交换两个数

posted @ 2008-02-01 13:22 浴盆 阅读(690) 评论(0) 编辑

C++中引用变量的用例

#include<iostream>
using namespace std;

int main()
{
    
int i = 1;

    
int &= i;           // 对变量I的引用

    cout
<<"i = "<<i<<"   "<<"address = "<<&i<<endl;
    cout
<<"x = "<<x<<"   "<<"address = "<<&x<<endl;

    
int y = 2;

    x 
= y;

    cout
<<"i = "<<i<<"   "<<"address = "<<&i<<endl;
    cout
<<"x = "<<x<<"   "<<"address = "<<&x<<endl;
    cout
<<"y = "<<y<<"   "<<"address = "<<&y<<endl;
    
    
return 0;
}
结果如下
i = 1 address = 0012ff6c
x= 1 address = 0012ff6c
i = 2 address = 0012ff6c
x= 2 address = 0012ff6c
y= 2address = 0012ff70

作为i的引用x,它们都指向相同的值和地址.
x=y;只是改变x的值,由于x是i的引用,所以,不能改变x的地址

posted @ 2008-02-01 12:54 浴盆 阅读(261) 评论(0) 编辑

关于strlen/sizeof函数在char和string类型中的应用

#include<iostream>
using namespace std;

int main()
{
//    typedef struct student 
//{
//       char name[10];
//       char sex; 
//       long sno; 
//       float score [4]; 
//} STU; 
//
//STU a[5];
//
//cout<<sizeof(a)<<endl;
//
//return 0;

    
char ghost[15= "galloping";
    
char * str = "galloping";

    
int n1 = strlen(ghost);             //字符数组中字符的实际长度
    int n2 = strlen(str);               //指针指向的字符数组的实际长度
    int n3 = strlen("galloping");       //字符串中字符的实际长度

    
int n4 = sizeof(ghost);             //字符数组分配空间大小
    int n5 = sizeof(str);               //指针分配的空间大小
    int n6 = sizeof("galloping");       //字符串分配空间大小,注意最后一位要加上'\0'

    cout 
<<"n1 = "<<n1<<endl;
    cout 
<<"n2 = "<<n2<<endl;
    cout 
<<"n3 = "<<n3<<endl;

    cout 
<<"n4 = "<<n4<<endl;
    cout 
<<"n5 = "<<n5<<endl;
    cout 
<<"n6 = "<<n6<<endl;

}
 

posted @ 2008-02-01 10:01 浴盆 阅读(737) 评论(0) 编辑