1、编写一个布尔函数int is_leap_year(int year),判断参数year是不是闰年。如果某年份能
被4整除,但不能被100整除,那么这一年就是闰年,此外,能被400整除的年份也是闰年。
1 #include <math.h> 2 #include <stdio.h> 3 4 int is_leap_year(int year){ 5 printf("%d ",year%4); 6 printf("%d ",!year%4); 7 if(year%4==0||year%400==1){ 8 return 1; 9 } 10 return 0; 11 } 12 13 int main(void){ 14 int year; 15 printf("Please input the year: "); 16 scanf("%d", &year); 17 // printf("%d ", year); 18 if(is_leap_year(year)){ 19 printf("%d is leap year. ", year); 20 }else{ 21 printf("%d is not leap year. ", year); 22 } 23 24 return 0; 25 }
2、编写一个函数double myround(double x),输入一个小数,将它四舍五入。例如myround(-3.51)的值是-4.0,myround(4.49)的值是4.0。可以调用math.h中的库函数ceil和floor实现这个函数。
1 #include <math.h> 2 #include <stdio.h> 3 4 double myround(double x){ 5 if(x>=0){ 6 return floor(x); 7 } 8 return -ceil(-x); 9 } 10 11 int main(void){ 12 double x; 13 printf("Please input the number x: ", x); 14 scanf("%lf", &x); 15 printf("The result is:%lf ", myround(x)); 16 return 0; 17 }
3、编写递归函数求两个正整数a和b的最大公约数(GCD,Greatest Common Divisor),使
用Euclid算法:
1). 如果a除以b能整除,则最大公约数是b。
2). 否则,最大公约数等于b和a%b的最大公约数。
1 #include <math.h> 2 #include <stdio.h> 3 4 int gcd(int a, int b){ 5 int mod; 6 if(a>b){ 7 mod = a%b; 8 if(mod == 0){ 9 return b; 10 } 11 return gcd(b, mod); 12 }else{ 13 mod = b%a; 14 if(mod == 0){ 15 return a; 16 } 17 return gcd(a, mod); 18 } 19 } 20 21 22 int main(void){ 23 int a, b; 24 printf("Please input a and b: "); 25 scanf("%d%d", &a, &b); 26 int gcdVal = gcd(a, b); 27 printf("The greatest common divisor is:%d ",gcdVal); 28 29 return 0; 30 }