1. (打印月历)输入月份m(1 ≤ m ≤ 12)按一定格式打印2015年第m月的月历。(第三、四空2.5分其余3分)
例如,2015年1月的月历打印效果如下(第一列为周日)
S M T W T F S
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
#include <iostream>
using namespace std;
const int dayNum[]={-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int m, offset, i;
int main() {
cin >> m;
cout << "S\tM\tT\tW\tT\tF\tS" << endl; // '\t'为TAB制表符
offset=4 ;
for (i = 1; i < m; i++)
offset = (offset+dayNum[i])%7 ;
for (i = 0; i < offset; i++)
cout << '\t';
for (i = 1; i <= dayNum[m] ; i++) {
cout << i ;
if (i == dayNum[m]|| (offset+i)%7 == 0)
cout << endl;
else
cout << '\t';
}
return 0;
}
2. (中位数)给定n(n为奇数且小于1000)个整数,整数的范围在0~m(0 < m < 2^31)之间,请使用二分法求这n个整数的中位数。所谓中位数,是指将这n个数排序之后,排在正中间的数。(第五空2分,其余3分)
#include <iostream>
using namespace std;
const int MAXN = 1000;
int n, i, lbound, rbound, mid, m, count;
int x[MAXN];
int main() {
cin >> n >> m;
for (i = 0; i < n; i++)
cin >> x[i];
lbound = 0;
rbound = m;
while ( rbound>lbound ) {
mid = (lbound + rbound) / 2;
count=0 ;
for (i = 0; i < n; i++)
if ( mid<x[i] )
count++ ;
if (count > n / 2)
lbound = mid + 1;
else
rbound=mid ;
}
cout << rbound << endl;
return 0;
}