Calculating percentages

Hello, I’ve recently gotten interested in java for making games. I like it because of it’s similarities to c/c++ (I never did get into basic), and it makes oop so much easier to me. Plus the mobile market is still young enough indie developers can still take advantage of it. Anyway I’ve been using “sams teach yourself java2” book to learn from and I’m going through all the excersises to get a better feel for the language. I was trying to calculate percentages from scratch for one excersise, but the program would only give me back zero for the division. Here’s the problem broken down to the nitty-gritty:

public class Percent
{
public static void main(String[] arguments)
{
double percent;

          //get the decimal value for 40%
          percent = (40/100);
          
          System.out.println(percent);
   }

}

Am I missing something? Is this kind of division taboo in java? Any help would be greatly appreciated, thanks for your time.

bsh % print(40/100);
0
bsh % print(40.0/100.0);
0.4

bsh % print(100.0/35.0);
2.857142857142857
bsh % print(100/35);
2

See the pattern? If you want double values append “.0”… if you want floats append “f”. With int there are no fractions.

percent = (40.0/100.0);

40 and 100 were both integers. So 40/100=0.4 as an integer is 0. Then it is auto cast to a double.

You need the 40.0 and 100.0 to tell the compiler that you are working with doubles all the way.

@BAD
as said, result of dividing integers is always an integer, I think it’s the same in C and C++ so freshen up on basics…

Ah, thanks everyone. It makes perfect sense. I was using literals after all. Kova, I don’t think this was something that mattered in c, but I could be wrong. Visual Studio lets you get away with a lot of things.

You are wrong.I even tested . :slight_smile: