programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Bear Bibeault
• Jeanne Boyarsky
• Tim Cooke
Sheriffs:
• Knute Snortum
• Junilu Lacar
• Devaka Cooray
Saloon Keepers:
• Ganesh Patekar
• Tim Moores
• Carey Brown
• Stephan van Hulst
• salvin francis
Bartenders:
• Ron McLeod
• Frits Walraven
• Pete Letkeman

# clarification on int division

Ranch Hand
Posts: 36
Im currently starting from scratch to refresh some java having been away for a while.
i was reading over HWS javanotes and came across this blurb, maybe someing can clear it up for me.

If N is an integer variable, then N/100 is an integer, and 1/N is equal to zero for any N greater than one! This fact is a common source of programming errors. You can force the computer to compute a real number as the answer by making one of the operands real: For example, when the computer evaluates 1.0/N, it first converts N to a real number in order to match the type of 1.0, so you get a real number as the answer.

why is 1/N equal to 0 if N > 1? ;where N is an int?

Ranch Hand
Posts: 1272
An int variable can only hold an integer (-1, 0, 1 ,2, etc.).

1/2 is actually 0.5, but integer division always truncates towards zero. The next lower integer to 0.5 is 0.

Ranch Hand
Posts: 98
The simple Logic behind it is that whenever you perform any operation like X/Y where X and Y both are integers, and if the answer is not a perfect interger then simple the digits after the decimal point . are removed.

so if answer of 5/2 is 2.50 then .50 is removed and 2 is given as a answer in interger format.

In case 1/N if N>1 then the real answer will always be 0.#### In this case all ####s are removed and 0 as a simple interger is returned as answer.

lowercase baba
Bartender
Posts: 12628
50
Remember in gradeschool, when you first learned how to divide (or at least, this is how I learned to do it)?

you would do something like

so 23 divided by 5 is 4, with a remainder of 3.

integer division does exactly this, then just throws the remainder away.

so when you do 1 / 1, you get 1 remainder 0.

when you do 1 / 2, you get 0, remainder 1...remainder thrown away, therefore you get 0.

1 / 3 is 0 remainder 1, throw away, 0... etc.

 It is sorta covered in the JavaRanch Style Guide.