Thinking Logic of computer programs (3)-Basic operations

Source: Internet
Author: User
Tags integer division

Operation

In the first section we talked about defining the data by variables, and we introduced the assignment of the data in the previous section, and after the initial value, the data can be evaluated. Computers are called "computational" machines because the main purpose of inventing them is to operate. There are different types of operations, and the operations supported by different data types are not the same, this article describes the main operations of basic type data in Java.

    • Arithmetic operations: mainly daily subtraction.
    • Comparison operations: The main daily size comparison
    • Logical operations: Operations on Boolean values

Arithmetic operations

The arithmetic operators have subtraction, the symbols are +-*/, and the modulo operator%, as well as the self-increment (+ +) and the Decrement (–) operators. Modulo operations apply to integers and character types, other arithmetic operations apply to all numeric types and character types, others are common sense, but character types look strange, and subsequent articles explain.

The minus sign (-) is usually used for two number subtraction, but it can also be placed in front of a number, such as-a, which means changing A's symbol, the original positive number will be negative, the original negative numbers will become positive, which is also in line with our common sense.

Modulus (%) is the remainder in mathematics, for example, 5%3 is 2,10%5 is 0.

Self-increment (+ +) and auto Minus (--) are shortcuts to adding one or minus one to yourself.

Subtraction most of the situation and the intuitive feeling is the same, it is easy to understand, but there are some areas to be aware of, and self-increment is slightly more complex, we explain below.

Subtraction Precautions

You should pay attention to the scope of the result and use the appropriate data type. Two positive numbers can be represented by an int, but the result of multiplying may be super, and the result will be confusing, for example:

int // 2147483647 is the maximum value that int can represent

The result of a is-2. Why is-2 we do not explain, in order to avoid this situation, our result type should use a long, but only to long is not enough, because the operation is the default by the int type, you need to represent at least one data as long, that is, after adding L or L, the following will appear the desired result:

long a = 2147483647*2l;

In addition, it is important to note that the integer division is not rounded, but rather directly to the decimal place, for example:

double d = 10/4;

The result is 2 instead of 2.5, if you want to operate on a decimal, you need to represent at least one number as a decimal, or you can use a forced type conversion, which is preceded by a number (double), which means that the number is treated as a double type, as in any of the following forms:

double d = 10/4.0; double d = 10/(double) 4;

Some of the above considerations, I think there is no special reason, it is probably convenient for language designers to implement the Language bar.

Fractional calculation results are imprecise

Whether you are using float or double, there are some very confusing phenomena that can occur when you perform operations, such as:

float f = 0.1f*0.1f; System.out.println (f);

The result seems to be self-evident, it should be 0.01, but in fact, the screen output is 0.010000001, followed by a 1. Swap double to see:

double d = 0.1*0.1; System.out.println (d);

Screen output 0.010000000000000002, a series of 0 after a 2, the result is not accurate.

What's going on? How can a computer be inaccurate when it seems such a simple calculation? But the fact is that, for the reasons, we need to understand the binary representations of float and double, followed by an analysis of the article.

Self-increment (+ +)/auto-Subtract (--)

Self-increment/decrement is to do one's own plus and minus one operation, but each has two forms, one is placed after the variable, such as a++, a--, and the other is placed before the variable, such as ++a,--a.

If you're just working on yourself, there's no difference between these two forms, except when there are other things to do. Put in the variable (a++), is to use the original value for other operations, and then modify themselves, and put in front of the variable (++a), is the first to modify their own, and then use the modified value for other operations. For example, a shortcut operation and its equivalent operations are:

Shortcut operations Equivalent operation
B=a++-1

B=a-1

A=a+1

c = ++a-1

A=a+1

C=a-1

ARRA[I++]=ARRB[++J]

J=j+1

ARRA[I]=ARRB[J]

I=i+1

Self-increment/decrement is a "fast" operation, it is to let the programmer write less code, but unfortunately, because of the strange syntax and strange behavior, give beginners some confusion.

Comparison operation

The comparison operation calculates the relationship between two values, and the result is a Boolean type (Boolean) value. The comparison operation applies to all numeric types and character types. Numeric types are easy to understand, but how do characters compare? A follow-up article explains.

Comparison operators are: greater than (>), greater than or equal to (>=), less than (<), less than or equal (<=), equals (= =), not equal to (! =).

Most of them are also more intuitive and need attention to be equal.

First, it uses two equals = = instead of an equal sign (=), why not use an equal sign? Because an equal sign (=) is already accounted for, it represents an assignment operation.

Also, for arrays, = = Determines whether the two array is the same array, not the element content of the two array, even if the contents of the two array are the same, but if it is two different arrays, = = will still return false, as follows:

int New int [] {A-I}; int New int [] {A-I}; // The result of A==b is false

If you need to compare the contents of an array, you need to compare each of the elements stored inside.

Logical operations

The logical operation generates a Boolean value of TRUE or false based on the logical relationship of the data. Logical operations can only be applied to Boolean data, but the result of a comparison operation is a Boolean value, so the comparison of other types of data can be performed logically.

The logical operators are as follows:

    • With (&): Two is true is true, as long as there is a false or false
    • or (|) : As long as there is a true is true, all is False is False
    • Non-(!) : True turns false for a variable, false turns True
    • XOR (^): two identical to False, two different true
    • Short circuit and (&&): Similar to &, the difference is explained immediately
    • Short Circuit or (| |) : Similar to |, the difference is explained at once

Most of the logical operations are more intuitive, and it is important to note that & and && The difference. If you are only doing logical operations, they are all the same, except in cases where there are other operations at the same time, such as:

Boolean true ; int b = 0; Boolean

Because A is true, flag is also true, but the result of B is 1, because | The following formula will also perform calculations, even if only a has known the result of flag, it will perform the subsequent operation. and | | is different if the code for the last sentence is:

Boolean

The value of B is still 0, because | | Will "short circuit", that is, in the See | | The previous section can be used to determine the results of the case, ignoring | | The subsequent operation.

In this example, we can also see that the self-increment/self-reduction operation brings us the trouble, other operations are simply crisp, assignment value assignment, addition on the addition, comparison, it is not mixed together, may write less code, but if the use of improper, will make the understanding much more difficult.

Operator Precedence

A slightly more complex operation may involve multiple variables, and a number of operations, which is the first, which is the calculation? The programming language dictates the precedence of the different operators, some will be counted first, some will be counted later, and in most cases, this priority is consistent with our common sense understanding.

But in some complex situations, we may not understand the sequence of operations. But we don't have to worry too much about it, we can use parentheses () to express the order we want, the parentheses are the first to do the arithmetic, in short, the parentheses are used when the order is indeterminate.

Summary

In this section we describe arithmetic operations, comparison operations, and logical operations, but we have left some problems, such as:

    • The result of the multiplication of positive integers is that there are negative numbers.
    • Very basic decimal arithmetic results are imprecise.
    • Character types can also be used for arithmetic operations and comparisons

What's going on here?

------------------

To be continued, check out the latest articles, please pay attention to the public number "old horse programming", in layman's words, explore the nature of Java programming and computer technology. Original article, All rights reserved.

Thinking Logic of computer programs (3)-Basic operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.