问题16_1
函数
f
u
n
fun
fun 的功能是:逆置数组元素中的值。
例如,若形参
a
a
a 所指数组中的数据最初排列为
:
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
:1, 2, 3, 4, 5, 6, 7, 8, 9
:1,2,3,4,5,6,7,8,9 ,则按规则移动后,数据排列为
:
9
,
8
,
7
,
6
,
5
,
4
,
3
,
2
,
1
:9, 8, 7, 6, 5, 4, 3, 2, 1
:9,8,7,6,5,4,3,2,1 。形参
n
n
n 中存放
a
a
a 所指数组中数据的个数。
代码16_1
#include<stdio.h>
void fun(int a[], int n){
int i,t;
for(i=0; i<n/2; i++){
t = a[i];
a[i] = a[n-1-i];
a[n-1-i] = t;
}
}
void main(void){
int b[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, i;
printf("\nThe original data:\n");
for(i=0; i<9; i++)
printf("%4d", b[i]);
printf("\n");
fun(b, 9);
printf("\nThe data after invert:\n");
for(i=0; i<9; i++)
printf("%4d", b[i]);
printf("\n");
}
结果16_1

问题16_2
函数
f
u
n
fun
fun的功能是:将一个由八进制数字字符组成的字符串转换成十进制整数。规定输入的字符最多只能包含
5
5
5 位八进制数字字符。
例如,若输入
77777
77777
77777,则输出为
32767
32767
32767。
代码16_2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int fun(char *p){
int n;
n = *p - '0';
p++;
while(*p!=0){
n = n*8 + *p - '0';
p++;
}
return n;
}
void main(void){
char s[6];
int i, n;
printf("Enter a string (octal digits):");
gets(s);
if(strlen(s)>5){
printf("Error:string too longer!\n\n");
exit(0);
}
for(i=0; s[i]; i++){
if(s[i]<'0'||s[i]>'7'){
printf("Error:%c not is octal digits!\n\n", s[i]);
exit(0);
}
}
printf("The original string:");
puts(s);
n = fun(s);
printf("\n%s is convered to intege number:%d\n\n", s, n);
}
结果16_2

问题16_3
学生的记录学号和成绩组成, N N N 名学生的数据已放入主函数中的结构体数组 s s s 中。请编写函数 f u n fun fun ,其功能是 : : : 函数返回该学号的学生数据,指定的学号在主函数中输入。若没有找到指定学号,在结构体变量中给学号置空串,给成绩置 − 1 -1 −1 ,作为函数值返回(用于字符串比较的函数是 s t r c m p strcmp strcmp)。
代码16_3
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 16
typedef struct{
char num[10];
int s;
}STREC;
STREC fun(STREC *a, char *b){
int i;
STREC str={"\0", -1}; // 若没找到指定的学号,在结构体变量中的学号置空串,给成绩置 -1
for(i=0; i<N; i++){
if(strcmp(a[i].num, b)==0) // 找到指定学号的学生数据
str = a[i];
}
return str; // 返回学生记录
}
void main(void){
STREC s[N] = {{"GA005", 85}, {"GA003", 76}, {"GA002", 69},
{"GA004", 85}, {"GA001", 91}, {"GA007", 72}, {"GA008", 64},
{"GA006", 87}, {"GA015", 85}, {"GA013", 91}, {"GA012", 66},
{"GA014", 91}, {"GA011", 66}, {"GA017", 64}, {"GA018", 64},
{"GA016", 72}};
STREC h;
char m[10];
int i;
printf("The original data:\n");
for(i=0; i<N; i++){
if(i%4==0)
printf("\n");
printf("%s %3d ", s[i].num, s[i].s);
}
printf("\n\nEnter the number:");
gets(m);
h = fun(s, m);
printf("The data:");
printf("\n%s %4d\n", h.num, h.s);
printf("\n");
}
结果16_3

897

被折叠的 条评论
为什么被折叠?



