曾經做過c++的打印月曆程序,輸入哪年哪月,打印出那一天月曆
最近學Python,驚呆了,import裏面自帶打印月曆,👍真是人生苦短,就學Python!
我們來對比一下呢:
打印月曆的C++代碼:
#include <iostream>
#include <iomanip>//輸出控制
#include <cstdlib>
#include <string>
#include <sstream>
#include <windows.h>
using namespace std;
int zeller(int yy, int mm)
{
int m = mm;
if (mm <= 2) {
yy = yy - 1;
m = 12 + mm;
}
else
{
m = mm;
}
int c = yy / 100;
int y = yy % 100;
int w = 700 + y + (y / 4) + (c / 4) - 2 * c + 26 * (m + 1) / 10 + 1 - 1;
//day 1;
w = w % 7;
return w;
}
int calcday1(int y, int m)
{
bool t;
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
t = true;
else
t = false;
int a[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if (t)
a[1] = 29;
return a[m - 1];
}
int calcday2(int y, int m)
{
bool t;
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
t = true;
else
t = false;
int a[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
if (t)
a[1] = 29;
return a[m - 1];
}
void gotoxy(unsigned char x, unsigned char y) {
COORD cor;
HANDLE hout;
cor.X = x;
cor.Y = y;
hout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hout, cor);
}
string putSpaceInt2str(int aNum)
{
stringstream res;
string s;
res << aNum;
res >> s;
s = " " + s;
return s;
}
int main()
{
int year, month;
cout << "輸入年 月" << endl;
cin >> year >> month;
int cc = zeller(year, month);//0->週日
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
cout << "一 二 三 四 五 六 日" << endl;
int d1, d2;
if (month == 1)
d1 = 31;
else
d1 = calcday1(year, month - 1);//上個月
d2 = calcday2(year, month);//本月
if (cc == 0)cc = 7; int s = 0;
d1 = d1 - cc + 2;
string str;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 4);
for (int i = cc - 1; i >= 1; i--) {
s++;
if (s % 7 == 0)
cout << endl;
if (d1 / 10 != 0)
cout << d1 << " ", d1++;
else {
//char c = d1 - '0';
//str = str + " " + c;
cout << " " << d1 << " ";
d1++;
}
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 10);
for (int i = 1; i <= d2; i++)
{
if (i / 10 != 0)
std::cout << i << " ";
else {
str = putSpaceInt2str(i);
std::cout << str << " ";
str = "";
}
s++;
if (s % 7 == 0)
std::cout << endl;
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 11);
for (int i = 1; s % 7 != 0; i++)
{
s++;
cout << " " << i << " ";
}
cout << endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 15);
return EXIT_SUCCESS;
}
有一點可怕,很長對不對?
下面再來看Python代碼:
# -*- coding = utf-8 -*-
# 引入日曆模塊
import calendar
# 輸入指定年月
yy = int(input("輸入年份: "))
mm = int(input("輸入月份: "))
# 顯示日曆
print(calendar.month(yy,mm))
輸出結果:
輸入年份: 2015
輸入月份: 6
June 2015
Mo Tu We Th Fr Sa Su
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
就這麼牛皮 ❗️
雖然C++中加了一點顏色,但還是比Python多的多