java2:前缀,后缀运算,取余的符号问题,字面量

本文详细解释了C++中前缀(++/--)和后缀(++/--)运算符的区别及用法。通过实例演示,帮助读者掌握不同运算符在表达式中的作用和返回值特性。

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

1 前缀,后缀运算

其实,我们一直都知道在任何一门语言中有前缀++,-- ,后缀++,--这样的运算,而在遇到简单的时候,也知道他是怎么用的,但是如果一遇到复杂的可能就有点蒙了,而有时候一些笔试题目就喜欢出这样的。例如 z=(x--)+(y++)+(--x)+(y++)这样的,有时候我们就不知道,每一步后,x,y在参与运算时候究竟算加、减后的还是算加减前的,但是今天看到书上原文是这么写的,恍然一悟,这时候就真真切切感受到看原版的好处了。

If the operator is before (prefixed to) the variable, the variable is incremented or decremented
by 1, then the new value of the variable is returned. If the operator is after (suffixed to) the vari-
able, then the variable is incremented or decremented by 1, but the original old value of the vari-
able is returned. Therefore, the prefixes  ++x and ——x are referred to, respectively, as the
preincrement operator and the predecrement operator; and the suffixes x++ and x—— are referred
to, respectively, as the postincrement operator and the postdecrement operator. 

注意里边说的,If the operator is after (suffixed to) the variable, then the variable is incremented or decremented by 1, but the original old value of the variable is returned.也就是说,我们++,--这种运算他也是一种表达式运算的,如果++ 作为后缀,那么该表达式(仅指后缀运算这一步)中的变量加上1,但是返回值是原值,你可以把它想成返回值不是原来的那个变量,而是另一个变量y。

所以,对于后缀,前缀运算我觉得一句话可以总结,就是运算改变了原来的变量,但是返回值用另一个变量来装。

那么我们来看下面的例子,

double x=1.0;

double y=5.0;

double z=x-- + (++y)  的值应该是 7.0  因为首先 x--使得x变为了0.0 但是该运算后返回的结果是1.0(你可以想成返回值放到了另一个变量n,而参与运算z=(x--)+(++y)是返回值n参与的运算),所以z=7.0

运行下面例子,试着解析下下面的k哦~~,紧紧记住上面红色说的就明白了:

double x=1.0;
		double y=5.0;
		double z=(x--)+(++y);
		double k=(++x)+(x++)+(y--)+(y++);
		System.out.println("z="+z+",,k="+k);
k的值是13,你猜对了么?

2 取余的符号问题

我们知道%用来取余,但是要知道在java中,余数也是有正负之分的哦(是不是感觉逼格很高~),余数的符号取决于被除数,跟被除数一致,所以-7%3=-1 ,-12 %3=0,-26%-8=-2,20%-13 =7;不信你试试~

3 字面量(或者叫直接量 literal)

因为这个词汇在后面经常会说到,尤其在说到String 时候关于是否同一对象的时候会用到的,所以这里也提一下,因为反正这篇知识点比较少,所以就杂一点吧。

literal A literal is a constant value that appears directly in a program. For example, 34 and 0.305
are literals in the following statements:
int numberOfYears = 34;
double weight = 0.305;

也就是说 ,直接量就是在程序中直接用的常量值,例如在int n=34, float fl=3.14f 这样中,34,31.4f就叫literal(字面量,直接量)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值