Can Someone Explain This To Me (Integer Division)

float x;
x=3/2;
println(x);

It prints 2.0 in the console. x is obviously not 2.0.

Is this some idiosyncrasy with println ?

Tagged:

Answers

  • println(3/2.); or println(3*.5);

  • Both 3 and 2 are integers (whole numbers) so when you ask Processing to calculate3 / 2 it will perform an integer division and return 1.

    3 divided by 2 is 1 remainder 1

    To get a decimal result one or both of the numbers must be of type float so

    float x; x = 3.0/2.0; println(x);

    will print 1.5

    So this is not a quirk of println rather a feature of the Java programming language.

  • Note the = symbol is the assignment operator and means calculate the expression on the right-hand-side and store the result in the variable on the left-hand-side. It has nothing to do with equality

  • Answer ✓

    Added to Common Questions

    https://forum.processing.org/two/discussion/24027/integer-division-why-does-2-5-0

    (copied from the Processing wiki troubleshooting guide, which doesn't allow linking to individual sections)

Sign In or Register to comment.