• 计算一个数的N次方,int和Integer的区别


    一:给定一个数d和n,如何计算d的n次方?例如:d=2,n=3,d的n次方为2^3=8.

    第一种方法是自定义计算:

    1. static double pow(double d,double n){
    2. if(n==0) return 1;
    3. if(n==1) return d;
    4. double result=1;
    5. if(n>0){
    6. result=1;
    7. for (int i = 0; i < n; i++) {
    8. result=result*d;
    9. }
    10. return result;
    11. }
    12. for(int i = 0; i < -n; i++) {
    13. result=result*d;
    14. }
    15. return 1/result;
    16. }

    第二种方法是使用java自带的函数:

    1. public static void main(String[] args) {
    2. double a=2;
    3. double b=-2;
    4. double m=Math.pow(a, b);
    5. System.out.println(m);
    6. }

    二:int和integer的区别

    1.数据类型不同:int是基础数据类型,而integer是包装数据类型;

    2.默认值不同:int的默认值是0,而Integer的默认值是null;

    3.内存中存储的方式不同:int在内存中直接存储的是数据值,而Integer实际存储的是对象引用,当new一个integer时实际上是生成一个指针指向此对象;

    4.实例化方式不同:Integer必须实例化才可以使用,而int不需要;

    5.变量的比较方式不同:int可以使用==来对比两个变量是否相等,而Integer一定要使用equals来比较两个变量是否相等。

    三.Integer和int的比较

    1.由于Integer实际是对一个integer对象的引用,所以两个通过New生成的integer变量永远不相同的,因为new生成的是两个不同的对象,其内存地址不同。

    1. public static void main(String[] args){
    2. Integer i1=new Integer(10);
    3. Integer i2=new Integer(10);
    4. System.out.println(i1.equals(i2));//true
    5. System.out.println(i1==i2);//false
    6. }

    2.非new生成的Integer变量指向的是Java常量池中的变量,而new出来的对象指向的是堆中新建的对象,两者内存地址不同。

    1. public static void main(String[] args){
    2. Integer i1=10;
    3. Integer i2=new Integer(10);
    4. System.out.println(i1==i2);//false
    5. }

    3.Integer变量和int变量进行比较时,只要两个变量的值相等,则结果就为true,(因为包装类Integer和基本数据类型比较的时候,java会自动拆箱为int,然后进行比较,实际上就是两个int变量进行比较)。

    1. public static void main(String[] args){
    2. int i1=new Integer(10);
    3. Integer i2=new Integer(10);
    4. System.out.println(i1==i2);
    5. }

    4.两个非new出来的Integer对象,进行比较的时候,如果两个变量的值区间在[-128~128)之间的时候,则返回的结果为true,如果两个变量的变量值不在这个区间,则比较的结果为false。

    1. public static void main(String[] args){
    2. Integer i1=-127;
    3. Integer i2=-127;
    4. System.out.println(i1==i2);//true
    5. Integer i3=-128;
    6. Integer i4=-128;
    7. System.out.println(i3==i4);//true
    8. Integer i5=-129;
    9. Integer i6=-129;
    10. System.out.println(i5==i6);//false
    11. }
    1. public static void main(String[] args){
    2. Integer i1=128;
    3. Integer i2=128;
    4. System.err.println(i1==i2);//false
    5. Integer i3=127;
    6. Integer i4=127;
    7. System.out.println(i3==i4);//true
    8. }

  • 相关阅读:
    Pandas数据分析21——固定时间点和时间差
    【漏洞复现】易思智能物流无人值守系统文件上传
    人工智能:ChatGPT与其他同类产品的优缺点对比
    计算机竞赛 深度学习图像修复算法 - opencv python 机器视觉
    使用Vue CLI安装和运行Vue3项目 [2022]
    Linux命令(96)之seq
    EMLP2021 | Google大模型微调经典论文prompt tuning
    【C++】最通俗的多态、虚表、虚指针讲解
    今天做了冰红茶
    细说tcpdump的妙用
  • 原文地址:https://blog.csdn.net/weixin_52014130/article/details/127419635