[C++]实验二:Pointer and Reference

// Expm2.1
/*
1.Write a function that is passed an array of n pointers to floats
and return a pointer to the maximum of the n floats.
*/

#include <iostream>
using namespace std;

float* Maximum(float *array[] ,const num)  //最大值函数
{
 float* max = array[0];
 for (int i=1; i<num ;i++)
        if( *array[i] > *max)
   max = array[i];
 return max;
}


void main()
{
 const int size=5; //定义数组长度
 float a=9.9,b=3.4,c=2.8,d=10.2,e=7.0;
 float *array[size]={&a,&b,&c,&d,&e};
    float* p=Maximum( array ,size );
 cout << "Max: " << *p << endl;
}

// 清翔兔

/*
2. Write a function atoi(const char* ) that take a C-style string containing digits
and returns the corresponding int. For example, atoi(“123) is 123.
Modify atoi() to handle C++ octal and hexadecimal notation in addition to plain decimal numbers.
*/

#include <iostream>
using namespace std;

double atoi(char* num)
{
 double inum=0;
 int i=0;
 int base=0;
 // 十六进制时,0X 或 0x 开头,如: 0xff
 if ( num[0]==48 && ( num[1]==88 || num[1]==120) )
 {
  i=0;
  while (num[i]!='/0')
  {
   if (num[i] >= 65 && num[i] <= 71)   //abcdef小写时
    num[i]-=7 ;
   if (num[i] >= 97 && num[i] <= 103)  //ABCDEF大写时
    num[i]-=39 ;
   i++;
  }
  base = 16;
  i=2;
 }
 // 八进制时,0 开头,如: 022
 else if ( num[0]==48 && ( num[1]>=48 && num[1]<=56) )
 {
  base = 8;
  i=1;
 }
 // 十进制时,以数字开头,如:90
 else if  ( num[0]>=48 && num[1]<=56)
  base = 10;
 else return 0;  //异常情况
 for( ; num[i]!='/0'; i++)
  inum = inum*base + num[i] - 48 ;
 return inum;
}


void main()
{
 char str[255];
 cout<<"Input a number (eg:  3200 or 0xff or 011):/n";
 gets(str);
 double istr = atoi(str);
 cout << istr << endl;
}

// 清翔兔

/*
Write a function that is passed two reference parameters
and make the values of the two string variables exchanged.
For example, at begin:
char* ap=“hello”;
char* bp=“how are you”
The exchanged result is:
char* ap=“how are you”;
char* bp=“hello”;
*/
#include <iostream>
using namespace std;

void exchange (char *&a ,char *&b)
{
 char *temp=b;
 b = a;
 a = temp;
}

void main()
{
 char* ap="hello";
 char* bp="how are you";
 cout << ap << " " <<bp << endl;
 exchange (ap,bp);
 cout << ap << " " <<bp << endl;
}

// 清翔兔

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值