目录
引言
就觉得填空题是没人看的,但觉得这次填空题还是有必要写一下题解
5-1 阅读程序,写出程序输出结果。
#include <stdio.h>
void swap(int x, int y)
{
int t;
t=x; x=y; y=t;
return;
}
int main(void)
{
int a=3, b=2;
swap(a, b);
printf("%d#%d#", a, b);
return 0;
}
3#2#
看到答案是不是有点迟疑,swap换了半天,a还是a,b还是b,那swap这个函数换了个寂寞。
但swap这里就是换了个寂寞。
因为swap换的是x,y,不是a,b,而x,y是什么?x,y是局部变量,只在swap函数范围内有效,所以大胆一点,swap这里就是没用。
那有没有办法让swap有用呢,答案肯定是有的,可以用指针
#include <stdio.h>
void swap(int *x, int *y)
{
int t;
t=*x; *x=*y; *y=t;
return;
}
int main(void)
{
int a=3, b=2;
swap(&a, &b);
printf("%d#%d#", a, b);
return 0;
}
可以看到,这时 a,b 就换了过来
5-2 程序阅读:
# include <stdio.h>
int s;
int f(int m)
{
static int k=0;
for(; k<=m; k++) s++;
return s;
}
int main(void )
{
int s=1;
s=f(2)+f(2);
printf("%d#%d#", s, f(20));
return 0;
}
6#21#
5-3
为鼓励居民节约用水,自来水公司采取按用水量阶梯式计价的办法,居民应交水费y(元)与月用水量x(吨)相关:当x不超过15吨时,y=4x/3;超过后,y=2.5x−10.5。请编写程序实现水费的计算,要求定义和调用函数fun(x)计算水费,其中x的类型是double,函数类型是double。
#include<stdio.h>
double fun(double x);
int main(){
double x=0,y=0;
scanf("%lf",&x);
y=fun(x);
printf("f(%.2f)=%.2f\n",x,y);
return 0;
}
double fun(double x){
double result;
if (x<=15){
result=4*x/3;
}else{
result=2.5*x-10.5;
}
return result;
}
一模一样的题,无需多言
5-4
编写一个函数fan(int m),计算参数m的各位数字之和。然后写出包括输入、输出和调用函数fan的主函数,请填空完成相应功能。
输入输出样例如下:
输入样例1:
234
输出样例1:
9
输入样例2:
12345
输出样例2:
15
int fan(int m){
int i,s=0;
do{
s=s+m%10;
m=m/10;
}while(m!=0);
return s;
}
#include <stdio.h>
int main(void){
int n=0,jg=0;
scanf("%d",&n);
jg=fan(n);
printf("%d\n",jg);
return 0;
}
也不知道题目为什么非要定义一个 i
5-5
老师想写一个用于交换变量x,y的值的swap 函数。
/*
这个很简单了吧,看上面,昨天已经写了一个类似的
*/
#include <stdio.h>
void swap(int *a,int *b);
int main() {
int x;
int y;
x=20;
y=16;
printf("x = %d\ny = %d\n",x,y);
swap(&x,&y);
printf("x = %d\ny = %d\n",x,y);
return 0;
}
void swap(int *a,int *b) {
int temp;
temp=*a;
*a=*b;
*b=temp;
}
题目很长,但就在第一题基础上,让你用指针实现swap的功能
5-6
输入正整数n,输出1!~n!的值。要求定义并调用含静态变量的函数fact_s(n)计算n!,其中n的类型是int,函数类型是double。
#include <stdio.h>
double fact_s(int n);
int main(void){
int i, n;
scanf("%d", &n);
for(i=1;i<=n;i++){
printf("%3d! = %.0f\n", i, fact_s(i));
}
return 0;
}
double fact_s(int n){
static float f=1;
f=f*n;
return f;
}
猜猜为什么用 float,不用int,那个 %.0f 不觉得绕弯子了吗
其实,我也不知道,我就是这么认为的
要我,我就用long double,问就是范围大
篇尾
static 静态局部变量:
1.属于静态存储类别
2.初始化只赋初值一次,以后每次调用时变量保留上次函数调用结束时的值
3.若未初始化、则自动初始化为0
4.函数调用结束后仍存在,但不能被其他函数引用