小练习

来源:互联网 发布:只有我知3出来了没有 编辑:程序博客网 时间:2024/04/30 07:12

今天有人让我帮他做点程序设计课设作业,悲催的我真的做了,表示不难~~嘿嘿

已知2007年一月一日为星期一。设计一函数按照下述格式打印2007年以后(含)某年某月的日历,2007年以前的拒绝打印。为完成此函数,设计必要的辅助函数可能也是必要的。

Calendar 2007-01

---------------------

Su Mo Tu We ThFrSa

--------------------

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

---------------------

//answer:#include<iostream>#include<iomanip>#define ERROR 0#define OK 1;using namespace std;int leapyear(int y){if(y%400==0||(y%100!=0&&y%4==0)) return OK;return ERROR;}int the_first_day(int y,int m){//计算每个月的第一天是星期几 int days=1;//这一个月的第一天是从2007第一天开始的第几天for(int i=2007;i<y;i++){if(leapyear(i))days+=366;else days+=365;}for(int i=1;i<m;i++){switch(i){case 1:case 3:case 5:case 7:case 8:case 10:case 12:days+=31;break;case 2:if(leapyear(y)) days+=29;else days+=28;break;case 4:case 6:case 9:case 11:days+=30;break;}}return days%7;   //0代表sun,1代表mon。,2代表tue...... }int main(){int y,m;cout<<"input year,month:"<<endl;while(cin>>y>>m){if(y<2007||m>12||m<1){cout<<"ERRPR,computer reject to print!"<<endl;return ERROR;}int week=the_first_day(y,m);cout<<"Calendar "<<y<<"-"<<m<<endl;cout<<"---------------------\nSu Mo Tu We Th Fr Sa\n--------------------"<<endl;for(int i=0;i<week;i++)cout<<"   ";int max=0,d=1;if(leapyear(y)&&m==2) max=28;else if(m==1||m==3||m==5||m==7||m==8||m==10||m==12) max=31;else if(m==2)max=28;else max=30;for(int t=week;d<=max;t++,d++){cout<<setw(3)<<d;if((t+1)%7==0)cout<<endl;}cout<<"\n---------------------"<<endl;}return OK;}//answer over


4-2-10已知

使用递归方法求解0<k<n的式子中间是加号)


//answer#include <iostream>using namespace std;int C(int n,int k){if(k==0) return 1;if(n==k) return 1;else return C(n-1,k)+C(n-1,k-1);}int main(){int n,k;while(cin>>n>>k){cout<<"input n,k:"<<endl;if(k>0&&k<n) cout<<C(n,k)<<endl;else{cout<<"ERRO!"<<endl;}}return 0;}//answer over


5-2-1编写一函数,返回1~6之间的随机数。这个过程模拟了掷骰子。

#include <stdio.h>#include <stdlib.h>#include <time.h>int RandomNumber(){int num;srand(time(NULL));num=rand()%(6)+1;return num;}int main(){int a;printf("随机输出1~6之间的某个数:\n");a=RandomNumber();printf("The random number is:");printf("%d\n",a);}


5-2-2继续上一题。编写一掷骰子游戏,计算机和用户充当对战的双方。首先由计算机生成一个随机数,然后接受用户输入的字符串“g”命令后生成用户的随机数(模拟用户掷了一次骰子),比较它们的大小,如果用户得到的随机数小于计算机得到的,则用户输了,否则输出用户赢了。

#include <stdio.h>#include <stdlib.h>#include <time.h>int RandomNumber(){int num=0;srand(time(NULL));num=rand()%(6)+1;return num;}int main(){int a,b;a=RandomNumber();printf("input a char:\n");char c;scanf("%c",&c);b=RandomNumber();printf("The random number is:");printf("%d  %d\n",a,b);if(b<a)printf("you fail!\n");else printf("you won!\n");}


原创粉丝点击