6-1 计算两个复数之积
本题要求实现一个计算复数之积的简单函数。
函数接口定义:
struct complex multiply(struct complex x, struct complex y);
其中struct complex
是复数结构体,其定义如下:
struct complex{
int real;
int imag;
};
裁判测试程序样例:
#include <stdio.h>
struct complex{
int real;
int imag;
};
struct complex multiply(struct complex x, struct complex y);
int main()
{
struct complex product, x, y;
scanf("%d%d%d%d", &x.real, &x.imag, &y.real, &y.imag);
product = multiply(x, y);
printf("(%d+%di) * (%d+%di) = %d + %di\n",
x.real, x.imag, y.real, y.imag, product.real, product.imag);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
3 4 5 6
输出样例:
(3+4i) * (5+6i) = -9 + 38i
代码
struct complex multiply(struct complex x, struct complex y)
{//函数返回类型是结构类型struct complex,参数类型是结构类型struct complex
struct complex result; //定义结构变量result,类型struct complex
result.real=x.real*y.real-x.imag*y.imag;//使用.访问结构的成员real和imag
result.imag=x.real*y.imag+x.imag*y.real;
return result; //返回结构变量结构变量result
}
6-2 按等级统计学生成绩
本题要求实现一个根据学生成绩设置其等级,并统计不及格人数的简单函数。
函数接口定义:
int set_grade( struct student *p, int n );
其中p
是指向学生信息的结构体数组的指针,该结构体的定义为:
struct student{
int num;
char name[20];
int score;
char grade;
};
n
是数组元素个数。学号num
、姓名name
和成绩score
均是已经存储好的。set_grade
函数需要根据学生的成绩score
设置其等级grade
。等级设置:85-100为A,70-84为B,60-69为C,0-59为D。同时,set_grade
还需要返回不及格的人数。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
struct student{
int num;
char name[20];
int score;
char grade;
};
int set_grade( struct student *p, int n );
int main()
{ struct student stu[MAXN], *ptr;
int n, i, count;
ptr = stu;
scanf("%d\n", &n);
for(i = 0; i < n; i++){
scanf("%d%s%d", &stu[i].num, stu[i].name, &stu[i].score);
}
count = set_grade(ptr, n);
printf("The count for failed (<60): %d\n", count);
printf("The grades:\n");
for(i = 0; i < n; i++)
printf("%d %s %c\n", stu[i].num, stu[i].name, stu[i].grade);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
10
31001 annie 85
31002 bonny 75
31003 carol 70
31004 dan 84
31005 susan 90
31006 paul 69
31007 pam 60
31008 apple 50
31009 nancy 100
31010 bob 78
输出样例:
The count for failed (<60): 1
The grades:
31001 annie A
31002 bonny B
31003 carol B
31004 dan B
31005 susan A
31006 paul C
31007 pam C
31008 apple D
31009 nancy A
31010 bob B
代码
int set_grade( struct student *p, int n )
{ //函数参数p是指向结构类型struct student的指针,指针指向结构数组,指针可以用[]取下标,与数组相似
int failed=0;
for(int i=0;i<n;i++)//for循环遍历
{
if(p[i].score<=59) //取结构数组下标为i的元素,该元素是一个结构,取该结构的成员score
{
p[i].grade='D';//取结构数组下标为i的元素,该元素是一个结构,取该结构的成员grade
failed++;
}else if(p[i].score<=69)
{
p[i].grade='C';
}else if(p[i].score<=84)
{
p[i].grade='B';
}else if(p[i].score<=100)
{
p[i].grade='A';
}
}
return failed; //返回不及格人数
}