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

本文介绍了两种计算d的n次方的方法,包括自定义计算和使用Java内置的Math.pow()函数。同时,详细阐述了int与Integer的区别,包括数据类型、默认值、内存存储、实例化和比较方式。在Integer对象比较时,讨论了常量池和堆内存的影响,以及特定数值范围内的比较结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

static double pow(double d,double n){
	if(n==0) return 1;
	if(n==1) return d;
	double result=1;
	if(n>0){
		result=1;
		for (int i = 0; i < n; i++) {
			result=result*d;
		}
		return result;
	}
	for(int i = 0; i < -n; i++) {
		result=result*d;
	}	
	return 1/result;
}

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

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

二: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生成的是两个不同的对象,其内存地址不同。

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

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

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

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

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

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

public static void main(String[] args){
		Integer i1=-127;
		Integer i2=-127;
		System.out.println(i1==i2);//true
	    Integer i3=-128;
		Integer i4=-128;
		System.out.println(i3==i4);//true
		Integer i5=-129;
		Integer i6=-129;
		System.out.println(i5==i6);//false
}
public static void main(String[] args){
	   Integer i1=128;
	   Integer i2=128;
	   System.err.println(i1==i2);//false
       Integer i3=127;
	   Integer i4=127;
	   System.out.println(i3==i4);//true
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值