C语言练习题
(所提供的源程序均采用自定义函数方式解决,如不采
用函数方式,也可直接在main函数中借鉴该思想编程,
因时间有限,所有程序未能一一—验证,仅供参考使用)
1定义一个函数intfun(inta,intb,intc),它的功能是:若a,b,c能构成等边三角
形函数返回3,若能构成等腰三角形函数返回 2,若能构成一般三角形函数返回1, 若不能构成三角形函数返回0。
#in clude<>
intfun (i nta,i ntb,i ntc)
{
if(a+b>c&&b+c>a&&a+c>b)
{
if(a==b&&b==c)
return3;
elseif(a==b||b==c||a==c)
return2;
elseretur n1;
}
elseretur n0;
}
voidmai n()
{
in ta,b,c,shape;
prin tf("\nl nputa,b,c:");
scan f("%d%d%d",&a,&b,&c);
prin tf("\na=%d,b=%d,c=%d\n",a,b,c);
shape=fu n( a,b,c);
prin tf("\n\n Theshape:%d\n",shape);
}
2、编写一个程序,将两个变量的值交换,例如变量a中的值原为3, b中的值原为
8,程序运行后a中的值为8,b中的值为3。
#include<>
voidfun(int*x,int*y) {
intt;
t=*x;*x=*y;*y=t } voidmain() { inta=3,b=8; printf("%d%d\n",a,b); fun(&a,b); printf("%d%d\n",a,b); }
,最小值放在变量c中。3、从键盘输入3个数,将最大值放在变量
,最小值放在变量c中。
例如,输入的数为: 551234, 输出结果应当是: a=,b=,c= 。
#include<> voidfun(float*p,float*q,float*s)
{
floatk;
if(*p
{k=*p;*p=*q;*q=k;}
if(*q
{k=*s;*s=*p;*p=k;}
if(*p
{k=*p;*p=*q;*q=k;}
}
voidmain()
{floata,b,c; printf("Inputabc:");scanf("%f%f%f",&a,&b,&c); printf("a=%,b=%,c=%\n\n",a,b,c);
fun(&a,&b,&c); printf("a=%,b=%,c=%\n\n",a,b,c);
}
4、编写函数fun(intn),它的功能是:计算正整数n的所有因子(1和n除外)之 和作为函数值返回。例如:n=120寸,函数值为239。
#include<>
#include<>
intfun(intn)
{
inti,s=0;
for(i=2;i
returns;
}
voidmain()/* 主函数*/
{
voidNONO();
printf("%d\n",fun(120));
NONO();
}
voidNONO()
{/*请在此函数内打开文件,输入测试数据,调用fun函数,
输出数据,关闭文件。 */
FILE*wf;
wf=fopen("","w");
fprintf(wf,"%d\n",fun(120));
fclose(wf);
}
5、计算 s, 并输出
111
S=1+— +++
1+21+2+31+2+3+…+n
n 通过键盘输入,例如:若 n 的值为 11 时,则函数值为: #include<> #include<> floatfun(intn)
{
inti; floats=,h=1; for(i=2;i<=n;i++) {
h=h+i;s=s+h;
} returns;
} voidmain() {
intn;floats; printf("\nPleaseenterN:");scanf("%d",&n); s=fun(n);
printf("theresultis:%f",s);
}
}
}
}
}
t中。高7531。6、将一个整数中的每一位上为奇数的数依次取出,构成一个新数放在 位仍在高位,低位仍在低位。例如,当s中的数为:时,
t中。高
7531。
voidfun(longs,long*t)
{
intd;
longs1=1;
*t=0;
while(s>0)
{
d=s%10;
if(d%2!=0)
{
*t=d*s1+*t;
s1=s1*10;
}
s/=10;
}
}
main()
{
longs,t;
printf("\nPleaseent