java - pat的一道题,有2个测试点一直无法通过
PHP中文网
PHP中文网 2017-04-18 10:16:07
0
3
389

pat的一道题

提交之后有两个测试点过不去

我的代码如下

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
        double fu = 0,ou = 0,a_2 = 0;
        int i = 0;
        if(s.charAt(0)==45){
            //如果是负数
            fu = 0.5;
        }
        while(i<s.length()){
            //判断2 的个数
            if((s.charAt(i)-48)==2){
                a_2++;
            }
            i++;    
        }
        if(s.charAt(s.length()-1)%2==0){
            //如果是偶数
            ou = 1.0;
        }
        double fan2 = 0;
        if(fu==0){//正数
            fan2 = a_2/((double)(s.length()));
                    
        }else{//负数        
            fan2 = a_2/(s.length()-1)*(ou+fu);
        }
        //测试2的个数/总字符串长度的值
        System.out.println(fan2);
        System.out.printf("%.2f%%",fan2*2*100);
    }
}

请问这是哪点没有通过呢?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
PHPzhong

The questioner did not understand the meaning of the question clearly. Negative numbers increase by 0.5 times and must be multiplied by 1.5. Even numbers increase by 1 and must be multiplied by 2.
fan2 = a_2/(s.length()-1)*(ou+fu ); // Are you multiplying the scale factor correctly?
Also positive numbers can also be even numbers. I don’t know how you passed the other cases

伊谢尔伦
// 这一行代码是有问题的,s.charAt()返回的是一个char值,而不是int值,这里会得到char对应的ascii值转换成int值再进行运算
if(s.charAt(s.length()-1)%2==0) {

In addition, as @zjupure said, I feel that the questioner’s understanding of the question is biased, and I also understood it according to @zjupure.

But the strange thing is that the questioner’s code also passed 66.67% of the tests...

In addition, some tests may not run because the boundary conditions and input parameter verification are not judged. For example, the input is not a number, or a value like +0, -0. The subject can also add these ( Although I think it’s fucked up to write these codes as algorithm questions, but in order to pass the test...).

刘奇

Additional point: If the first digit is a negative sign, then you need to start from the second digit to calculate whether it is 2, and the number of digits in the number

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!