p;Width; }float GetLength() { return Length; }
float GetWidth() { return Width; }
private:
float Length;
float Width;
};
void main()
{
float length, width;
cout << "请输入矩形的长度:";
cin >> length;
cout << "请输入矩形的宽度:";
cin >> width;
Rectangle r(length, width);
cout << "长为" << length << "宽为" << width << "的矩形的面积为:"
<< r.GetArea () << endl;
}
程序运行输出:
请输入矩形的长度:5
请输入矩形的宽度:4
长为5宽为4的矩形的面积为:20
8.编写一个函数,统计一个英文句子中字母的个数,在主程序中实现输入、
#include <iostream.h>
#include <stdio.h>
int count(char *str)
{
int i,num=0;
for (i=0; str[i]; i++)
{
if ( (str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z') )
num++;
}
return num;
}
void main()
{
char text[100];
cout << "输入一个英语句子:" << endl;
gets(text);
cout << "这个句子里有" << count(text) << "个字母。" << endl;
}
程序运行输出:
输入一个英语句子:
It is very interesting!
这个句子里有19个字母。
9.编写一个矩阵转置的函数,矩阵的维数在程序中由用户输入。
#include <iostream.h>
void move (int matrix[3][3])
{
int i, j, k;
for(i=0; i<3; i++)
for (j=0; j<i; j++)
{
k = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = k;
}
}
void main()
{
int i, j;
int data[3][3];
cout << “输入矩阵的元素” << endl;
for(i=0; i<3; i++)
for (j=0; j<3; j++)
{
cout << “第” << i+1 << “行第” << j+1
<<”个元素为:“;
cin >> data[i][j];
}
cout << “输入的矩阵的为:” << endl;
for(i=0; i<3; i++)
{
for (j=0; j<3; j++)
cout << data[i][j] << ” “;
cout << endl;
}
move(data);
cout << “转置后的矩阵的为:” << endl;
for(i=0; i<3; i++)
{
for (j=0; j<3; j++)
cout << data[i][j] << ” “;
cout << endl;
}
}
程序运行输出:
输入矩阵的元素
第 1 行第1 个元素为:1
第1 行第2 个元素为:2
第1 行第3 个元素为:3
第2 行第1 个元素为:4
第2 行第2 个元素为:5
第2 行第3 个元素为:6
第3 行第1 个元素为:7
第3 行第2 个元素为:8
第3 行第3 个元素为:9
输入的矩阵的为:
1 2 3
4 5 6
7 8 9
转置后的矩阵的为:
1 4 7
2 5 8
3 6 9
10.编写函数int index(char *s, char *t),返回字符串t 在字符串s中出现的最左边的位置,如果在s中没有与t匹配的子串,就返回-1。
解:
源程序:
#include <iostream.h>
int index( char *s, char *t)
{
int