问题13_1
函数
f
u
n
fun
fun 的功能是:把形参
s
s
s 所指字符串中下标为奇数的字符右移到下一个奇数位置,最右边被移出字符串的字符绕回放到第一个奇数位置,下标为偶数的字符不动(注:字符串的长度大于等于2)。
例如,形参
s
s
s 所指字符串为
"
a
b
c
d
e
f
g
h
"
"abcdefgh"
"abcdefgh" ,执行结果为
"
a
h
c
b
e
d
g
f
"
"ahcbedgf"
"ahcbedgf" 。
代码13_1
#include<stdio.h>
void fun(char *s){
int i, n, k;
char c;
n = 0;
for(i=0; s[i]!='\0'; i++)
n++;
if(n%2==0)
k = n-1;
else
k = n-2;
c = s[k]; // *(s+k)
for(i=k-2; i>=1; i=i-2){
s[i+2] = s[i];
s[i] = c;
}
}
void main(void){
char s[80] = "abcdefgh";
printf("\nThe original string is:%s\n", s);
fun(s);
printf("\nThe result is:%s\n", s);
}
结果13_1
问题13_2
函数
f
u
n
fun
fun的功能是:求表达式
s
=
a
a
⋅
⋅
⋅
a
a
−
⋅
⋅
⋅
−
a
a
a
−
a
a
−
a
s\ =\ aa···aa\ -\ ···\ -\ aaa\ -aa\ -\ a
s = aa⋅⋅⋅aa − ⋅⋅⋅ − aaa −aa − a
(此处
a
a
⋅
⋅
⋅
a
a
aa···aa
aa⋅⋅⋅aa 表示
n
n
n 个
a
a
a ,
n
n
n 和
a
a
a 的值在
1
˜
9
1\ \~\ 9
1 ˜9)。
例如,若给
a
=
5
,
n
=
6
a=5\ ,\ n=6
a=5 , n=6,则以上表达式为:
s
=
333333
−
⋅
⋅
⋅
−
333
−
33
−
3
s\ =\ 333333\ -\ ···\ -\ 333\ -33\ -\ 3
s = 333333 − ⋅⋅⋅ − 333 −33 − 3
其值是
296298
296298
296298 。
n
n
n 和
a
a
a 是
f
u
n
fun
fun 函数的形参,表达式的值作为函数值传回
m
a
i
n
main
main 函数。
代码13_2
#include<stdio.h>
long fun(int a, int n){
int j;
long s=0, t=0;
for(j=0; j<n; j++)
t = t*10+a;
s = t;
for(j=1; j<n; j++){
t = t/10;
s = s-t;
}
return s;
}
void main(void){
int a, n;
printf("\nPlease enter a and n:");
scanf("%d %d", &a, &n);
printf("The value of function is %ld\n", fun(a, n));
}
结果13_2
问题13_3
编写函数
v
o
i
d
f
u
n
(
c
h
a
r
∗
t
t
,
i
n
t
p
p
[
]
)
void\ fun(char\ *tt,\ int\ pp[\ ])
void fun(char ∗tt, int pp[ ]) ,统计在
t
t
tt
tt 所指的字符串中
"
a
"
"a"
"a" 到
"
z
"
"z"
"z" 26个小写字母各自出现的次数,并依次放在
p
p
pp
pp 所指的数组中。
例如,但输入字符串
"
a
b
c
d
e
f
g
a
b
c
d
e
a
b
c
"
"abcdefgabcdeabc"
"abcdefgabcdeabc" 后,程序的输出结果应当是:
3
3
3
2
2
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
3\ 3\ 3\ 2\ 2\ 1\ 1\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0\ 0
3 3 3 2 2 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
代码13_3
#include<stdio.h>
#include<string.h>
void fun(char *tt, int pp[]){
int i;
for(i=0; i<26; i++){
pp[i] = 0;
}
for(; *tt!='\0'; tt++){
if(*tt>='a' && *tt<='z')
pp[*tt-'a']++;
}
}
void main(void){
char aa[1000];
int bb[26], k;
printf("\nPlease enter a char string:");
scanf("%s", aa);
fun(aa, bb);
for(k=0; k<26; k++)
printf("%d", bb[k]);
printf("\n");
}