第一次上機考試補題報告
R7-4 求某月的天數
題目:
輸入年份year、月份month,判斷該月的天數。閏年:能被4整除但不能被100整除或者能被400整除的年份是閏年。
輸入格式:
測試資料有多組,處理到檔案尾。對於每組測試,輸入兩個整數,表示年份year和月份month。
輸出格式:
對於每組測試,輸出對應年月的天數。
考試時的程式碼:
#include<stdio.h> int main() { int year=0,month=0; do { scanf("%d %d",&year,&month); if((year%4==0&&year%100!=0)||year%400==0) { if(month==2) { printf("29\n",month); }else if(month==4||month==6||month==9||month==11) { printf("30\n"); }else { printf("31\n"); } }else { if(month==2) { printf("28\n",month); }else if(month==4||month==6||month==9||month==11) { printf("30\n"); }else { printf("31\n"); } } }while(month>0&&month<=12); return 0; }
可以發現該程式碼未能完成題目中讀取到檔案尾的要求,加入while(scanf()!=EOF)就能完成題目要求。
改後代碼:
#include<stdio.h> int main() { int year=0,month=0; while(scanf("%d %d",&year,&month)!=EOF) { if((year%4==0&&year%100!=0)||year%400==0) { if(month==2) { printf("29\n",month); }else if(month==4||month==6||month==9||month==11) { printf("30\n"); }else { printf("31\n"); } }else { if(month==2) { printf("28\n",month); }else if(month==4||month==6||month==9||month==11) { printf("30\n"); }else { printf("31\n"); } } } return 0; }
R7-6 列印沙漏
題目:
當n=5時,沙漏圖形如輸出樣例所示。請觀察並明確沙漏圖形的規律。要求輸入一個整數n,輸出滿足規律的沙漏圖形。
輸入:
測試資料有多組,處理到檔案尾。每組測試輸入一個整數n(1<n<20)。
輸出:
對於每組測試,輸出滿足規律的沙漏圖形。
考試時程式碼:
#include<stdio.h> int main() { int n=2,f=0,i=0,a=0,t=0; while(n>1&&n<20) { scanf("%d",&n); if(n<=1||n>=20) { break; } f=2*n-1; for(i=1;i<=n;i++) { for(t=1;t<=i;t++) { if(i!=n) printf(" "); } for(a=1;a<=f-(i-1)*2;a++) { if(i!=n) { printf("*"); } } if(i!=n) printf("\n"); } for(i=n;i>=1;i--) { for(t=i;t>=1;t--) { printf(" "); } for(a=f-(i-1)*2;a>=1;a--) { printf("*"); } printf("\n"); } } return 0; }
可以發現該程式碼不能讀取到檔案尾,因此也需要同上一題一樣加上while(scanf()!=EOF),且該程式碼輸出圖形為:
觀察可發現:該圖形每行都多了一個空格
因此程式碼可以改成:
#include<stdio.h> int main() { int n=2,f=0,i=0,a=0,t=0; while(scanf("%d",&n)!=EOF) { if(n<=1||n>=20) { break; } f=2*n-1; for(i=1;i<=n;i++) { for(t=1;t<i;t++) { if(i!=n) printf(" "); } for(a=1;a<=f-(i-1)*2;a++) { if(i!=n) { printf("*"); } } if(i!=n) { printf("\n"); } } for(i=n;i>=1;i--) { for(t=i;t>1;t--) { printf(" "); } for(a=f-(i-1)*2;a>=1;a--) { printf("*"); } printf("\n"); } } return 0; }
R7-5 位運算應用
題目:
現有96個埠狀態,用3個無符號整型ua(95~64),ub(63~32),uc(31~0)組合起來的96位二進位制數來表示,每位二進位制數的1、0表示其正常和故障狀態。
輸入一個tag位,將tag位上二進位制數置1.
tag位表示其在96位中所處的位數(在96位中從低向高從0至95)
輸入格式:
第一行輸入三個無符號整數,表示ua,ub,uc
第二行輸入一個整數tag。
輸出格式:
若tag值不在0到95之間,則輸出Error
,否則輸出轉換後的ua,ub,uc
考試時沒太看懂題目,考完之後寫了一下程式碼
#include<bits/stdc++.h> int main() { unsigned int ua,ub,uc; int tag; scanf("%u %u %u",&ua,&ub,&uc); scanf("%d",&tag); if(tag<0||tag>95) { printf("Error"); } else { switch(tag/32) { case 0:uc|=(unsigned int)1<<tag%32;break; case 1:ub|=(unsigned int)1<<tag%32;break; case 2:ua|=(unsigned int)1<<tag%32;break; } printf("ua=%u,ub=%u,uc=%u",ua,ub,uc); } return 0; }