i,j,k;
for(i = 0; s[i] != ‘\0′; i++)
{
for(j = i, k = 0; t[k] != ‘\0′ && s[j] == t[k]; j++, k++);
if (t[k] ==’\0′)
return i;
}
return -1;
}
void main()
{
int n;
char str1[20],str2[20];
cout << “输入一个英语单词:”;
cin >> str1;
cout << “输入另一个英语单词:”;
cin >> str2;
n = index(str1,str2);
if (n > 0)
cout << str2 << “在” << str1 << “中左起第” << n+1
<< “个位置。”<<endl;
else
cout << str2 << “不在” << str1 << “中。” << endl;
}
11.编写函数reverse(char *s)的倒序递归程序,使字符串s倒序。
解:
源程序:
#include <iostream.h>
#include <string.h>
void reverse(char *s, char *t)
{
char c;
if (s < t)
{
c = *s;
*s = *t;
*t = c;
reverse(++s, –t);
}
}
void reverse( char *s)
{
reverse(s, s + strlen(s) – 1);
}
void main()
{
char str1[20];
cout << “输入一个字符串:”;
cin >> str1;
cout << “原字符串为:” << str1 << endl;
reverse(str1);
cout << “倒序反转后为:” << str1 << endl;
}
12.一个Shape基类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square。
解:
#include <iostream.h>
#include <math.h>
#define pi 3.14
class shape
{ public:
virtual float area()=0;
};
class circle:public shape
{
private:
float r;
public:
circle(float r1)
{
r=r1;
}
float area()
{
return (float)pi*r*r;
}
};
class rectangle:public shape
{
private:
float width,height;
public:
rectangle(float w1,float h1)
{
width=w1;height=h1;
}
float area()
{
return width*height;
}
};
class square : public rectangle
{
public:
square(float len):rectangle(len,len){};
~square(){};
float area(float len)
{
return len * len;
};
};
int main()
{
shape* s[2];
s[0]=new circle(1);
cout<<s[0]->area()<<endl;
s[1]=new rectangle(2,4);
cout<<s[1]->area()<<endl;
s[ 2 ] = new square( 3 );
cout << s[2]->area() << endl;
for( int i = 0; i < 3; i++ )
{
delete [] s[ i ];
}
return 0;
}
|