PAT乙級 1001(C)+1054(Java)
阿新 • • 發佈:2018-12-11
準備一天兩道題,就這樣吧,先從水題開始。
分析:看懂題就應該寫出來了,注意邊界與0情況的處理。
#include<stdio.h> #include<math.h> int main(void){ int n; scanf("%d",&n); if(n>1000 || n==0) { exit(-1); } int i=0; while(n!=1) { if(n%2==0 && n!=0) { n=n/2; } else { n=(3*n+1)/2; } i++; } printf("%d",i); return 0; }
分析:其實如果用c寫,處理字串還是有些複雜的。
這裡偷個懶,Java的parse和string.format直接解決了判別字串的問題;至於錯誤資訊輸出,用丟擲異常的方式處理。
思路還是很清晰的,少有的(?)java沒有超時的題目。
有時間補個C的。注意格式中的空格,以及java提交不能有包名。
import java.util.Scanner; public class Main { public static void main(String[]args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int count=0; double mysum=0; for(int i=0;i<n;i++){double x= 0; String s=null; try{ s=in.next(); x=Double.parseDouble(s); double tmp = Double.parseDouble(String.format("%.2f", x)); if(x>1000 || x<-1000||Math.abs(tmp-x)>=0.001){ //最多2位小數 throw new NumberFormatException(); } count++; mysum += x; }catch(NumberFormatException e) { System.out.println("ERROR: "+s+" is not a legal number"); } } in.close(); if(count==0) { System.out.printf("The average of 0 numbers is Undefined"); }else if(count==1) { System.out.printf("The average of 1 number is %.2f",mysum); }else { System.out.printf("The average of %d numbers is %.2f", count,mysum/count); } } }