PAT Grade Exam 1001 A + B Format code to achieve learning and knowledge

Ready to participate in September of nine PAT grade certificate exam on the subject on the site were analyzed:

1001 title A + B Format (20 minutes)

Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

The value of b + a is calculated and output in a format and their sum (the desired number in a set of three numbers per output, separated by a comma) When the sum is less than four digits need not be separated by commas

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where 106​​a,b106​​. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

Code:

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int b = in.nextInt();
            int sum;
            sum=a+b;
            if(Math.abs(sum)<1000) 
        {
            System.out.println(sum);
        }
        else
        {
            System.out.format("%,d%n",sum);
        }
        }
    }
}

Run shot:

problem analysis:

Simple digital sum problem, the key is not to get out of the digital phase plus, in digital format output and how the requirements in accordance with the subject of the last added by this issue and I learned a few things, then summarize :

 

When the absolute value sum is less than 1000, to the normal output.

When the absolute value sum is not less than 1000, the format required by the output. The main method used in the code System.out.format (), followed by its introduction.

 

The following two links from learned a lot: https: //segmentfault.com/a/1190000017828119

                                                   https://blog.csdn.net/u012246458/article/details/52634175

In the previous study, we have seen the use printand printlnmethod to print the string to the standard output ( System.out), since all numbers can be converted to a string , you can use these methods to print out any mix of strings and numbers, however, Java there are other ways of programming languages, can be more control over the printout when that contain numbers.

printf and format Methods

java.io包中包含一个PrintStream类,它有两种格式化方法可用于替换printprintln,这些方法,formatprintf,彼此相同。你一直使用的熟悉的System.out恰好是PrintStream对象,因此你可以在System.out上调用PrintStream方法,因此,你可以在以前使用printprintln的代码中的任何位置使用formatprintf,例如:

System.out.format(.....);

格式说明符以百分号()开头,以转换器结束,转换器是一个字符,指示要格式化的参数类型,在百分号()和转换器之间,你可以使用可选的标志和说明符,java.util.Formatter中记录了许多转换器、标志和说明符。

这是一个基本的例子:

int i = 461012;
System.out.format("The value of i is: %d%n", i);

%d指定单个变量是十进制整数,%n是与平台无关的换行符,输出是:

 
The value of i is: 461012

下表列出了表格后面的示例程序TestFormat.java中使用的一些转换器和标志。


以下程序显示了你可以使用格式进行的一些格式化,输出显示在嵌入注释中的双引号内
import java.util.Calendar;
import java.util.Locale;

public class TestFormat {
    
    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
      
      double pi = Math.PI;

      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE,
                        "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"

      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"

      System.out.format("%tD%n", c);    // -->  "05/29/06"
    }
}

DecimalFormat类

你可以使用java.text.DecimalFormat类来控制前导和尾随零、前缀和后缀、分组(千)分隔符和小数分隔符的显示,DecimalFormat在数字格式化方面提供了极大的灵活性,但它使你的代码更复杂。

下面的示例通过将模式字符串传递给DecimalFormat构造函数来创建DecimalFormat对象myFormatter。然后,myFormatter会调用DecimalFormatNumberFormat继承的format()方法 — 它接受double值作为参数,并返回字符串中的格式化数字:

这是一个示例程序,说明了DecimalFormat的用法:

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

输出是:

123456.789  ###,###.###  123,456.789
123456.789  ###.##  123456.79
123.78  000000.000  000123.780
12345.67  $###,###.###  $12,345.67

下表说明了每行输出:

一些具体实例:

 

DecimalFormat format 方法

大家在format()一个小数是,总是对格式中的'0'和'#'有些不解吧!

eg: 

    1:new DecimalFormat("00.000").format(pi) //结果:03.142

    2:new DecimalFormat("##.###").format(pi) //结果:3.142

都是对pi进行格式化,但第一个的结果是03.142,第二个的结果是3.142

这是什么原因呢?

0和#都是占位符,但在不同的地方,作用不一样。下面对他们做了具体的比较。

希望对大家有所帮助。

0: 

    比实际数字的位数多,不足的地方用0补上。

    new DecimalFormat("00.00").format(3.14)  //结果:03.14

    new DecimalFormat("0.000").format(3.14)  //结果: 3.140

    new DecimalFormat("00.000").format(3.14)  //结果:03.140

    比实际数字的位数少:整数部分不改动,小数部分,四舍五入

    new DecimalFormat("0.000").format(13.146)  //结果:13.146

    new DecimalFormat("00.00").format(13.146)  //结果:13.15

    new DecimalFormat("0.00").format(13.146)  //结果:13.15

#: 

    比实际数字的位数多,不变。

    new DecimalFormat("##.##").format(3.14)  //结果:3.14

    new DecimalFormat("#.###").format(3.14)  //结果: 3.14

    new DecimalFormat("##.###").format(3.14)  //结果:3.14

    比实际数字的位数少:整数部分不改动,小数部分,四舍五入

    new DecimalFormat("#.###").format(13.146)  //结果:13.146

    new DecimalFormat("##.##").format(13.146)  //结果:13.15

    new DecimalFormat("#.##").format(13.146)  //结果:13.15


其他的一些用法,(添加百分号,千分号,科学计数法,自定义正负数模板)
可参照
http://jff.iteye.com/blog/576737
http://blog.csdn.net/marcoleung/article/details/176514

BigDecimal类:

由于1中的方法保留两位小数,最后一位会四舍五入,所以用BigDecimal 来截取小数点后两位

下面是相关的方法:

BigDecimal.setScale()方法用于格式化小数点

setScale(1)表示保留一位小数,默认用四舍五入方式 

setScale(1,BigDecimal.ROUND_DOWN)直接删除多余的小数位,如2.35会变成2.3 

setScale(1,BigDecimal.ROUND_UP)进位处理,2.35变成2.4 

setScale(1,BigDecimal.ROUND_HALF_UP)四舍五入,2.35变成2.4

setScaler(1,BigDecimal.ROUND_HALF_DOWN)四舍五入,2.35变成2.3,如果是5则向下舍

setScaler(1,BigDecimal.ROUND_CEILING)接近正无穷大的舍入

setScaler(1,BigDecimal.ROUND_FLOOR)接近负无穷大的舍入,数字>0和ROUND_UP作用一样,数字<0和ROUND_DOWN作用一样

setScaler(1,BigDecimal.ROUND_HALF_EVEN)向最接近的数字舍入,如果与两个相邻数字的距离相等,则向相邻的偶数舍入。



注释:

1:scale指的是你小数点后的位数。比如123.456则score就是3.

score()就是BigDecimal类中的方法啊。

比如:BigDecimal b = new BigDecimal("123.456");

b.scale(),返回的就是3.

2:roundingMode是小数的保留模式。它们都是BigDecimal中的常量字段,有很多种。

比如:BigDecimal.ROUND_HALF_UP表示的就是4舍5入。

3:pubilc BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)

的意思是说:我用一个BigDecimal对象除以divisor后的结果,并且要求这个结果保留有scale个小数位,roundingMode表示的就是保留模式是什么,是四舍五入啊还是其它的,你可以自己选!

4:对于一般add、subtract、multiply方法的小数位格式化如下:

BigDecimal mData = new BigDecimal("9.655").setScale(2, BigDecimal.ROUND_HALF_UP);

        System.out.println("mData=" + mData);

----结果:----- mData=9.66

END(以后若有相关知识会继续补充)

 

 

 

 

 

 

 
 

 

 

 




Guess you like

Origin www.cnblogs.com/daimasanjiaomao/p/10984337.html