PAT乙级 1001(C)+1054(Java)

准备一天两道题,就这样吧,先从水题开始。

1001.点击查看

分析:看懂题就应该写出来了,注意边界与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;
}

1054.点击查看

分析:其实如果用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);
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/keelongz/p/10100146.html