简体   繁体   English

为什么这个计算不起作用?

[英]Why doesn't this calculation work?

I was throwing together a quickie program to take mainframe output blocked in 133 byte lengths, all ending with a CRLF, and it was working except for my calculated number of lines in the output.我正在编写一个快速程序来获取阻塞在 133 字节长度的大型机输出,所有输出都以 CRLF 结尾,并且除了我计算出的输出行数外,它正在工作。 Because the output size was X pages of 133 bytes with 2 bytes (CRLF) at the end, I was calculating the line count as:因为输出大小是 133 个字节的 X 页,最后是 2 个字节(CRLF),所以我计算行数为:

lineCount = fileLength - 2 / 133;

For a file length of 3194, that works out to 24 lines.对于 3194 的文件长度,计算为 24 行。 Take 3194, subtract 2 for the CRLF and you get 3192, and that is divided by 133 to come up with 24. Simple!取 3194,为 CRLF 减去 2,得到 3192,然后除以 133 得到 24。简单! The crazy thing is, I was getting the lineCount equal to the fileLength !疯狂的是,我得到的lineCount等于fileLength

What could I be doing wrong?我可能做错了什么?

After examining this several times, I finally hit on it!看了好几遍,终于上手了! It's a matter of the infamous Order of Operations !这是臭名昭著的行动顺序问题

lineCount = fileLength - 2 / 133;

If I evaluate this from left to right, according to my description above, it works fine, but I happen to be a human, not a CPU.如果我从左到右评估这个,根据我上面的描述,它工作正常,但我碰巧是人,而不是 CPU。 Different rule!不同的规则! The computer processor has to use a different rule: MiDAS: multiplications, divisions, additions and subtractions.计算机处理器必须使用不同的规则:MiDAS:乘法、除法、加法和减法。

My code was calculating 2 / 133, which for integers equals 0. It was then subtracting that 0 from fileLength, and of course set lineCount to that value.我的代码正在计算 2 / 133,对于整数,它等于 0。然后从 fileLength 中减去 0,当然也将 lineCount 设置为该值。 I am ancient of days, sort of, and should have known better from the start, but I guess I was in a hurry.我是古老的时代,某种程度上,从一开始就应该知道得更好,但我想我很着急。 The correct code?正确的代码?

int lineCount = ((fileLength - 2) / 133);

So, remember MiDAS and you will be Golden!所以,记住MiDAS,你将成为金牌!

NOTE: it's more complicated than this, actually.注意:实际上,它比这更复杂。 The full rule encompasses parentheses and exponentiation.完整规则包括括号和取幂。 For an expanded look at this check Wikipedia for Order of Operations .有关此检查的扩展查看 Wikipedia for Order of Operations

In the US the mnemonic is more like: PEMDAS - Please Excuse My Dear Aunt Sally - and refers to Parentheses, Exponents, Multiplications, Divisions, Additions and Subtractions.在美国,助记符更像是:PEMDAS - 请原谅我亲爱的莎莉阿姨 - 指的是括号、指数、乘法、除法、加法和减法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM