PTA作业(第一次)--函数题

  1. 函数调用
    编写三个函数:求两个整数的最大值、最小值、和。分别用这三个函数作为实参,再写一个计算函数compute,对两个整数进行各种计算。其中一个形参为指向具体算法函数的指针。
点击查看代码
#include <iostream>
using namespace std;

int max(int a, int b);
int min(int a, int b);
int sum(int a, int b);
int compute(int a, int b, int(*func)(int, int));

int main()
{
int a, b, res;
 cin >> a >> b;
res = compute(a, b, & max);
cout << "Max of " << a << " and " << b << " is " << res << endl;
res = compute(a, b, & min);
cout << "Min of " << a << " and " << b << " is " << res << endl;
res = compute(a, b, & sum);
cout << "Sum of " << a << " and " << b << " is " << res << endl;
return 0;
}

/* 请在这里填写答案 */
int max(int a, int b){
	return a>b?a:b;
}
int min(int a, int b){
	return a<b?a:b;
}
int sum(int a, int b){
	return a+b;
}
int compute(int a, int b, int(*func)(int, int)){
	return func(a,b);
}
  1. 构成新数
    给定函数fun的功能是:将长整型数中每一位上为偶数的数依次取出,构成一个新数放在t中。高位仍在高位,低位仍在低位。例如,当s中的数为:87653142时,t中的数为:8642。
点击查看代码
#include <stdio.h> 
void fun (long s, long *t);
int main()
{ long s, t;
 scanf("%ld", &s);
 fun(s, &t);
 printf("The result is: %ld\n", t);
 return 0;
}


/* 请在这里填写答案 */
void fun (long s, long *t){
     int count=1;
     int t1;
     *t=0;
    while (s){
        int t1=s%10;
        if(t1%2==0){
            *t=*t+t1*count;
            count*=10;
        }
        s/=10;
    }
}
  1. 函数指针
    梦山高中现需要将某普通班的最优秀学生调整入理科实验班。为此,将从两个方面考察学生,一是数学和英语两门课的总分;另一个是所有四门课的总分。分别找出两科总分和全科总分的第一名,并从中决定调整人选。
    输入将首先输入学生数n, (n为不超过80的正整数);接下来依次输入各位学生的学号,数学、英语、语文、理科综合成绩。学号及四科成绩均为不超过300的正整数。
    输出时:第一行输出两科总分第一的学号,第二行输出四科总分第一的学号。 约定在两位学生成绩相同时,优先选择学号较小的学生;各位学生的学号均不相同。
点击查看代码
#include <iostream>
using namespace std;
const int N=80;
struct Student{
  int num;
  int score[4];
};

/* 请在这里填写答案 */
bool s2(const Student &a,const Student &b){
    if(a.score[0]+a.score[1]==b.score[0]+b.score[1])return a.num<b.num;
    else return a.score[0]+a.score[1]>b.score[0]+b.score[1];
}
bool s4(const Student &a,const Student &b){
    if(a.score[0]+a.score[1]+a.score[2]+a.score[3]==b.score[0]+b.score[1]+b.score[2]+b.score[3])return a.num<b.num;
    else return a.score[0]+a.score[1]+a.score[2]+a.score[3]>b.score[0]+b.score[1]+b.score[2]+b.score[3];
}
int select(Student st[],int n,bool (*s)(const Student &,const Student &)){
    int maxnum=0;
    for(int i=1;i<n;i++){
        if(s(st[maxnum],st[i]))
            continue;
        else 
            maxnum=i;
    }
    return st[maxnum].num;
}
int main()
{
  int i, j, k, n;
  bool s2(const Student &, const Student &);
  bool s4(const Student &, const Student &);
  Student st[N];
   cin>>n;
   for(i=0;i<n;i++){
      cin>>st[i].num;
      for(j=0;j<4;j++) cin>>st[i].score[j];
    }
   cout<<select(st, n, s2)<<endl;
   cout<<select(st, n, s4)<<endl;
}
posted @ 2022-04-26 15:57  21CodeXin  阅读(184)  评论(0)    收藏  举报