例5.1 输入两个数,按代数值由小到大的顺序输出这两个数
#include<stdio.h>
void main()
{
float a,b,t;
scanf("%f,%f",&a,&b);
if(a>b)
{
t=a;
a=b;
b=t;
}
printf("%5.2f,%5.2f",a,b)
}
例5.2 输入3个数a、b、c,要求按由小到大的顺序输出
#include<stdio.h>
void main()
{
float a,b,c,t;
scanf("%f,%f,%f",&a,&b,&c);
if(a>b)
{
t=a;
a=b;
b=t;
}
if(a>c)
{
t=a;
a=c;
c=t;
}
if(b>c)
{
t=b;
b=c;
c=t;
}
printf("%5.2f,%5.2f,%5.2f\n",a,b,c);
}
例5.3 有一函数:
-1 (x<0)
y= 0 (x=0) 编一程序,输入一个x的值,输出y值。
1 (x>0)
#include<stdio.h>
void main()
{
int x,y;
scanf("%d",&x);
if(x<0)
y=-1;
else
if(x==0) y=0;
else
y=1;
printf("x=%d,y=%d\n",x,y);
}
例5.4 输入一个字符,判别它是否大写字母,如果是,将它转换成小写字母;如果不是不转换。然后输出最后得到的字符。
#include<stdio.h>
void main()
{
char ch;
scanf("%c",&ch);
ch=(ch>='A' && ch<='Z')? (ch+32):ch;
printf("%c\n",ch);
}
例5.5 写程序,判断某一年是否润年。
#include<stdio.h>
void main()
{
int year,leap;
scanf("%d",&year);
if(year%4==0)
{
if(year%100==0)
{
if(year%400==0)
leap=1;
else
leap=0;
}
else
leap=1;
}
else
leap=0;
if(leap)
printf("%d is ",year);
else
printf("%d id not",year);
printf("a leap year.\n");
}
例5.6 求方程ax2+bx+c=0方程的解。
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,disc,x1,x2,realpart,imagpart;
scanf("%f,%f,%f",&a,&b,&c);
printf("The equation ");
if(fabs(a)<=1e-6)
printf("is not quadratic\n");
else
{
disc=b*b-4*a*c;
if(fabs(disc)<=1e-6)
printf("has two equal roots:%8.4f\n",-b/(2*a));
else
if(disc>1e-6)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("has distinct real roots:%8.4f and %8.4f\n",x1,x2);
}
else
{
realpart=-b/(2*a);
imagpart=sqrt(-disc)/(2*a);
printf("has complex roots:\n");
printf("%8.4f+%8.4fi\n",realpart,imagpart);
printf("%8.4f-%8.4fi\n",realpart,imagpart);
}
}
}
例5.7 运输公司对用户计算运费。
#include<stdio.h>
void main()
{
int c,s;
float p,w,d,f;
scanf("%f,%f,%d",&p,w,s);
if(s>=3000) c=12;
else c=s/250;
switch(c)
{
case 0:d=0;break;
case 1:d=2;break;
case 2:
case 3:d=5;break;
case 4:
case 5:
case 6:
case 7:d=8;break;
case 8:
case 9:
case 10:
case 11:d=10;break;
case 12:d=15;break;
}
f=p*w*s*(1-d/100.0);
printf("freight=%15.4f\n",f);
}