Untitled Document

三、编程题
1．写3×3矩阵转置程序。
#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;
}
}
2. 编程实现两字符串的连接，要求使用字符数组保存字符串(要求不使用库函数)。
#include <iostream.h>
void main()
{
int i=0,j=0;
char s1[200],s2[100];
cout << "请输入第一个字符串：";
cin >> s1;
cout << "请输入第二个字符串：";
cin >>s2;
while(s1[i])
i++;
while(s2[j])
s1[i++] = s2[j++];
s1[i] = '\0';
cout << "连接后的字符串为：" << s1 << endl;
}
3. 写统计输入的正文中有多少单词的程序，这里的单词指的是用空白符分隔开的字符串。
#include <stdio.h>
void main()
{
int c,n;
bool inword;
n = 0;
inword = false;
while((c = getchar()) != EOF)
if(c == ' '||c == '\t'||c == '\n')
inword = false;
else if(inword == false)
{
inword = true;
n ++;
}
printf("There are %d words\n",n);
}
4．参考程序如下：
#include <iostream.h>
const MAX_STR_LENGTH = 100;

void main()
{
char str[MAX_STR_LENGTH];

/* 输入部分 */
cout<<"Input a string:";
cin>>str;

/* 加密部分 */
for(int i = 0; i < MAX_STR_LENGTH; i++)
{
if(str[i] == '\0') break;
str[i] = str[i] + 2;
}

/* 输出部分 */
cout<<"加密后的字符串为："<<str<<endl;
}
程序输出结果如下：
Input a string:China
加密后的字符串为：Ejkpc

5． 答：
#include<iostream.h>
int binary_search(int array[],int value,int size)
{
int found=0;
int high=size,low=0,mid;
mid=(high+low)/2;
cout<<"Looking for: "<<value<<endl;
while((!found)&&(high>=low))
{
cout<<"low mid high "<<endl;
cout<<low<<" "<<mid<<" "<<high<<endl;
if(value==array[mid])
found=1;
else if(value<array[mid])
high=mid-1;
else
low=mid+1;
mid=(high+low)/2;
}
return((found)? mid: -1);
}
void main(void)
{
int array[100],i;
for(i=0;i<100;i++)
array[i]=i;
cout<<"Result of search: "<<binary_search(array,33,100)<<endl;
cout<<"Result of search: "<<binary_search(array,76,100)<<endl;
cout<<"Result of search: "<<binary_search(array,566,100)<<endl;
}