5-3 if...else if ...else...if...else语句 if的多层嵌套
#include <stdio.h>
int main(void) {
char c;
c=getchar();
if(c == '+')
printf("plus\n");
else if(c == '-') printf("minus\n");
else if(c == '*') printf("multiplication\n");
else if(c == '/') printf("division\n");
else printf("error\n");
return 0;
}
/*intput:
+
*/
/*
plus
*/
5-5 条件表达式
求输入的两个整数中较小的一个
#include <stdio.h>
int main(void) {
int a,b,min;
scanf("%d%d",&a,&b);
min=a<b?a:b;
printf("min = %d\r\n",min);
return 0;
}
/*intput:
12 18
*/
/*
12
*/
5-6 输入三个数 按由小到大输出
#include <stdio.h>
int main(void) {
int a,b,c,t;
scanf("%d%d%d",&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("the sorted number is :%d %d %d\r\n",a,b,c);
return 0;
}
/*intput:
12 18 2
*/
/*
the sorted number is :2 12 18
*/
5-7 求方程 ax^2+bx+c=0的解
#include <stdio.h>
#include <math.h>
int main(void) {
double a,b,c,disc,x1,x2,realpart,imagpart;
scanf("%lf,%lf,%lf",&a,&b,&c);
disc=b*b-4*a*c;
if(fabs(disc)<=1e-6) //b^2-4ac == 0,计算输出两个相等实根
printf("has two equal roots:%8.4lf\r\n",-b/(2*a));
else if(disc>1e-6) //>0 两个不相等的实数根
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("has distinct real roots:%8.4lf %8.4lf\r\n",x1,x2);
}
else{
realpart = -b/(2*a);
imagpart = sqrt(-disc)/(2*a);
printf("has complex roots:\n%8.4lf+%8.4lf\r\n",realpart,imagpart);
printf("%8.4lf-%8.4lf\r\n",realpart,imagpart);
}
return 0;
}
/*intput:
5,3,7
*/
/*
has complex roots:
-0.3000+ 1.1446
-0.3000- 1.1446
*/
5-8 输入年号和月号,计算该年该月共几天
#include <stdio.h>
#include <math.h>
int main(void) {
int year,month,days = 0;
scanf("%d,%d",&year,&month);
printf("%d,%d",year,month);
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:days = 31;break;
case 4:
case 6:
case 9:
case 11:days = 30;break;
case 2:
if(year%4==0&&year%100!=0 || year%400==0)
days=29;
else
days=28;
default:
printf("data error\r\n");
}
printf("year = %d,month= %d,days= %d\r\n",year,month,days);
return 0;
}
/*intput:
2021,9
*/
/*
2021,9year = 2021,month= 9,days= 30
*/