• 三元操作符 、窄化转化


    温故而知新,可以为师矣。书读百遍,其义自见。我们多数人都知道这个道理,但是极少数人能够做到重复的学习,现在我也是在温故,让自己更加充实起来。说个题外话:在外面遇到事情的时候,一定要敢于张口。

    让一两个小例子,帮我们温习下三元运算符/if-else,字符串操作符+、+=以及在执行窄化转换时,截尾与舍入的问题。

    例1 三元操作符 boolean-exp ? value0 : value1 当boolean-exp表达式返回值为true时,结果为value0 ; 返回为false时,结果为value1. 而if-else同样是符合那个条件,执行其下面的语句。字符串的+、+=的运算也是在该例子中,+是拼接字符串。

    package com.date0531;

    public class Test_0531_Demo01 {
    static int ternary(int i){
    return i < 10 ? i * 100 : i * 10;
    }
    static int standardIfElse(int i){
    if(i < 10){
    return i * 100;
    }
    else
    return i * 10;
    }
    public static void main(String[] args){
    System.out.println(ternary(9));
    System.out.println(ternary(10));
    System.out.println(standardIfElse(9));
    System.out.println(standardIfElse(10));
    int x = 0, y = 2, z = 4;
    String s = "x, y, z";
    System.out.println(s+x+y+z);
    System.out.println(x+" "+s);
    s += "(summed) = ";
    System.out.println(s+(x+y+z));
    System.out.println(" "+x);
    }
    }

    运行结果:

    例2 在执行窄化转化时,必须注意截尾和舍入问题。例如,如何将一个浮点值转换为整型值,总是对该数字执行截尾。如果想要得到舍入的结果,就需要使用java.lang.Math中的round()方法;

    package com.date0531;

    public class Test_0531_Demo02 {
    public static void main(String [] args){
    double d1 = 0.7, d2 = 0.4;
    float f1 = 0.7f, f2= 0.4f;
    System.out.println("(int)d1: " + (int)d1);
    System.out.println("(int)d2: " + (int)d2);
    System.out.println("(int)f1: " + (int)f1);
    System.out.println("(int)f2: " + (int)f2);
    //float double 转型为整型值时,总是对该数字执行截尾。

    double above = 0.7, below = 0.4;
    float fabove = 0.7f, fbelow = 0.4f;
    System.out.println("Math.round(above): " +Math.round((above)));
    System.out.println("Math.round(below): " +Math.round((below)));
    System.out.println("Math.round(fabove): " +Math.round((fabove)));
    System.out.println("Math.round(fbelow): " +Math.round((fbelow)));
    //想要舍入的结果需要使用java.lang.Math中的round()方法;
    }
    }

    运行结果:

    千万不要小看,任意一个基础哦

    
    
    
    
    
    
  • 相关阅读:
    Codeforces 877 C. Slava and tanks
    Codeforces 877 D. Olya and Energy Drinks
    2017 10.25 NOIP模拟赛
    2017 国庆湖南 Day1
    UVA 12113 Overlapping Squares
    学大伟业 国庆Day2
    51nod 1629 B君的圆锥
    51nod 1381 硬币游戏
    [JSOI2010]满汉全席
    学大伟业 2017 国庆 Day1
  • 原文地址:https://www.cnblogs.com/zhishifx/p/9120206.html
Copyright © 2020-2023  润新知