(一)编程题
1、输入3个整数,按由小到大的顺序输出,然后将程序改为:输入3个字符串,按由小到大顺序输出(使用引用和指针的方式)
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
int *p1,*p2,*p3,t;
p1=&a,p2=&b,p3=&c;
cout<<"输入三个整数:"<<endl;
cin>>a>>b>>c;
if(*p1>*p2)
{
t=*p1;
*p1=*p2;
*p2=t;
}
if(*p1>*p3)
{
t=*p1;
*p1=*p3;
*p3=t;
}
if(*p2>*p3)
{
t=*p2;
*p2=*p3;
*p3=t;
}
cout<<"输出:"<<a<<" "<<b<<" "<<c;
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[10],b[10],c[10],t[10];
char *p1,*p2,*p3;
p1=a,p2=b,p3=c;
cout<<"输入三个字符串:"<<endl;
cin>>a>>b>>c;
if((strcmp(p1,p2)>0))
{
strcpy(t,p1);
strcpy(p1,p2);
strcpy(p2,t);
}
if((strcmp(p1,p3)>0))
{
strcpy(t,p1);
strcpy(p1,p3);
strcpy(p3,t);
}
if((strcmp(p2,p3)>0))
{
strcpy(t,p2);
strcpy(p2,p3);
strcpy(p3,t);
}
cout<<"输出:"<<a<<" "<<b<<" "<<c;
return 0;
}
- 将n个数按输入时顺序的逆序排列
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
void convert(int *,int);
int n,i,a[20];
int *p;
cout<<"输入数的个数为:";
cin>>n;
cout<<"输入数字:";
for(i=0;i<n;i++)
cin>>a[i];
p=&a[0];
convert(p,n);
cout<<"逆序输出:"<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
void convert(int *p,int n){
int temp;
int i;
int *a;
a=p;
for(i=0;i<n/2;i++){
temp=*(a+i);
*(a+i)=*(a+n-1-i);
*(a+n-1-i)=temp;
}
}
3、编写一个函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度
#include <iostream>
using namespace std;
int main()
{
int length(char *p);
int len;
char str[20];
cout<<"输入字符串:";
cin>>str;
len=length(str);
cout<<"字符串的长度是: "<<len<<endl;
return 0;
}
int length(char *p) //求字符串长度的函数
{
int n=0;
while (*p!='\0')
{
n++;
p++;
}
return(n);
}
4、输入10个整数,将其中最小的数与第1个数对换,把最大的数与最后1个数对换。写3个函数:①输入10个数;②进行处理;③输出10个数。
#include<iostream>
using namespace std;
int main()
{
int a[10],i;
cout << "请输入十个数:" << endl;
for (i = 0;i < 10;i++)
cin >> a[i];
int *p = a, max, min,max_i=0,min_i=0,t;
max = *p;
for (i = 1;i < 10;i++)
{
if (*(p + i) > max)
{
max = *(p + i);
max_i = i;
}
}
t = *(p + 9);
*(p + 9) = max;
*(p+max_i) = t;
min = *p;
for (i = 1;i < 10;i++)
{
if (*(p + i) < min)
{
min = *(p + i);
min_i = i;
}
}
t = *p;
*p = min;
*(p+min_i) = t;
for (i = 0;i < 10;i++)
cout << *(p+i)<<" ";
return 0;
}
- 输入一行文字,找出其中大写字母、小写字母、空格、数字以及其他字符各有多少(使用指针)
#include<iostream>
#include <stdio.h>
using namespace std ;
int main()
{
int upper= 0, lower=0 ,digit=0, space=0,other=0 ,i=0 ;
char *p;
char a[80];
cout<<"请输入一行文字:"<<endl;
while ((a[i] = getchar()) != '\n')
i++;
p = &a[0];
while(*p!='\n')
{
if((*p>='A' )&&(*p<='Z'))
++upper;
else if((*p>='a')&&(*p<='z'))
++lower;
else if((*p>='0')&&(*p<='9'))
++digit;
else if((*p==' '))
++space;
else
++other;
p++;
}
cout<<"大写字母个数:"<<upper<<endl
<<"小写字母个数:"<<lower<<endl
<<"数字个数:"<<digit<<endl
<<"空格个数:"<<space<<endl
<<"其他字符个数:"<<other<<endl;
return 0;
}