1、假设变量x和n是两个正整数,我们知道x/n这个表达式的结果要取Floor,例如x是17,n是4,则结果是4。如果希望结果取Ceiling应该怎么写表达式呢?例如x是17,n是4,则结果是5;x是16,n是4,则结果是4。
答: (x+n-1)/n
(1). 设x=kn,k为整数,即x为n的整数倍。则(x+n-1)/n=(kn+n-1)/n=((k+1)n-1)/n,此时分子没有达到n的k+1倍,但大于等于n的k倍, 默认计算取下整则为k。符合要求。
(2).设x=kn+m,k为整数,m为整数且0<m<n。则(x+n-1)/n=(kn+m+n-1)/n=((k+1)n+m-1)/n。此时分子的大于等于(k+1)n,小于(k+2)n,按照默认计算应该为k+1。符合要求。
2、编写一个布尔函数int is_leap_year(int year),判断参数year是不是闰年。如果某年份能被4整除,但不能被100整除,那么这一年就是闰年,此外,能被400整除的年份也是闰年。
1
2 3 4 5 6 7 8 9 10 11 12 13 |
int is_leap_year(
int year)
{ if (year % 4 == 0 && year % 400 != 0) { if (year % 100 != 0) return 1; else return 0; } else if (year % 400 == 0) return 1; else return 0; } |
3、编写一个函数double myround(double x),输入一个小数,将它四舍五入。例如myround(-3.51)的值是-4.0,myround(4.49)的值是4.0。可以调用math.h中的库函数ceil和floor实现这个函数。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
double myround(
double x)
{ int sa = 0, si = 0; if (x == 0. 0) return 0. 0; else if (x > 0. 0) { sa = ( int)x; si = x + 0. 5; if (sa == floor(si)) return sa; else return sa + 1; } else { sa = ( int)x; si = x - 0. 5; if (sa == ceil(si)) return sa; else return sa - 1; } } |
4、编写递归函数求两个正整数a和b的最大公约数,编写递归函数求Fibonacci数列的第n项
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
int gcd(
int greater,
int less)
{ if (greater % less == 0) return less; else return gcd(less, (greater % less)); } long int fibonacci( int n) { if (n == 0 || n == 1) return 1; else return fibonacci(n - 1) + fibonacci(n - 2); } |
5、编写程序数一下1到100的所有整数中出现多少次数字9。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
int count_9 (
void)
{ int i, n = 0; for (i = 1; i <= 100; i++) { if (i / 10 == 9) { if (i % 10 == 9) n = n + 2; else n = n + 1; } else if (i % 10 == 9) n = n + 1; } return n; } |
6、编写程序打印一个不重复的九九乘法表,编写函数diamond打印一个菱形。diamond(int , char);
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
void printf_99 (
void)
{ int i, j; for (i = 1; i <= 9; i++) { for ( j = 1; j <= 9; j++) if (i >= j) printf( "%d\t", i * j); printf( "\n"); } } void diamond( int num, char pattern) { int row, col; if (num % 2 == 0) { printf( "num must be even!\n"); return; } for (row = -num; row <= num; row++) { for ( col = -num; col <= num; col++) { if (fabs(row) + fabs(col) <= num) printf( "%c", pattern); else printf( " "); } printf( "\n"); } } |
7、实现一个用分子分母的格式来表示有理数的结构体rational以及相关的函数,rational结构体之间可以做加减乘除运算,运算的结果仍然是rational。
1
2 3 4 5 6 7 8 9 10 |