【C和C++】一些课后习题的解法
P219 输入年月日计算是该年的第几天
#include<stdio.h> int main() { int year,month,day; scanf("%d%d%d",&year,&month,&day); int runian(int month,int day); int frunian(int month,int day); if((year%4==0)&&(year%100!=0)) printf("%d\n",runian(month,day)); else if((year%100==0)&&(year%400==0)) printf("%d\n",runian(month,day)); else printf("%d\n",runian(month,day)+1); return 0; } int runian(int month,int day) { int a[12]={31,28,31,30,31,30,31,30,30,31,30,31}; for(int i=0,sum=0;i<(month-1);i++) {sum+=a[i];} return sum+day; }
P291 约瑟夫环 逢3退出
#include <stdio.h> #include<stdlib.h> int main() { int n, i, k, m; int array[50], *p; printf("n = \n"); scanf("%d", &n); p = array; for (i = 0; i < n; i++) *(p+i) = i+1; i = 0; // i 为每次循环计数变量 k = 0; // k 为按1,2,3报数时的计数变量 m = 0; // m为退出人数计数变量 while(m < n-1) //当退出人数比n-1少时执行循环体 { if( *(p+i) != 0 ) k++; if(k == 3) // 对退出的人编号置为0 { *(p+i) = 0; k = 0; m++; } i++; if(i == n) i = 0; } while(*p == 0) p++; printf("No. %d\n", *p); return 0; }
Vedic Square and Vedic Star
#include<iostream> using namespace std; int main() { int j; int i; int k; int a[100][100]={0}; for (i = 1; i<10; i++) a[i][0]=i; for (j = 1; j<10; j++) a[0][j]=j ; for (i = 1; i < 10;i++) { for (j = 1; j < 10;j++) { a[i][j] = a[i][0]*a[0][j]; k= a[i][j]; if (a[i][j]>9) a[i][j] = k / 10 + k % 10; if (a[i][j] > 9){ k = a[i][j]; a[i][j] = k / 10 + k % 10; } } } for (i = 0; i<10; i ++) { for (j = 0; j < 10; j++) if (j ==9) cout << a[i][j] << endl; else cout << a[i][j] ; } int h; cin>>h; for (i = 1; i<10; i ++) { for (j = 1; j < 10; j++) if (h==a[i][j]) cout << '*' ; else cout <<' ' ; cout<<'\n'; } return 0; }
elevator
# include <iostream> using namespace std; int main(){ int a[100]={0}; int n; int i; int sum=0; cin>>n; sum=n*5; for (i=1;i<=n;i++){ cin>>a[i]; } for (i=1;i<=n;i++){ if(a[i]>a[i-1]) sum+=6*(a[i]-a[i-1]); else sum+=4*(a[i-1]-a[i]); } cout<<sum<<endl; return 0; }
约瑟夫环
指针
void Joseph(Node*head,int n,int m) { int i,int j; Node*p,*q; q=head;p=q->next; for(j=1) { for(i=1;i<n;i++){ q=p;p=p->next; } printf("%d",p->number); q->next=p->next; p=q->next; free(q->next); } }
数组
void Jopseph(int n,int m) { int jopseph[]; int i=0;int j=n;//i用来计数,j用来改变数组的允许访问长度 for(int a=0;a++;a<=n) { joseph[a]=a+1; } for(int a=0;a++;a<j) { i+=1; if(a+1>j) { a=0; } if(i==m) { printf("%d",joseph[a]); for(int b=a;b++;b<j) { joseph[b]=joseph[b+1]; j-=1; } } } }