If anybody studies or studied computer science , can you help me with this code?

here's the code:
public class voume {

public static void main (String[] args) {
double height= 9;
double diameter=8;
double volume=3.14*height*diameter;
System. out. println (volume);
double litre=1/1000;
double litres= volume*litre;
System. out. println (litres);
but for some reason whenever it prints , litres become 0.0 even though it should be 0.22608
can anyone tell me what's wrong?


Most Helpful Guy

Have an opinion?

What Guys Said 3

  • I didn't run the program but I bet you this line is your problem.

    double litre=1/1000;

    1 and 1000 are integers so the result of the division is also an int which gets cast to double when you assign it. It's called type coercion and it's one of the many hidden gotcha's that will give you headaches when you're programming.

    You could change it to double litre =1.0 / 1000.0 and it would probably work fine but I don't understand why you don't just say double litres= volume / 1000.0;

    • Yeah that was the problem
      I didn't because it didn't cross my mind , now I feel mega stupid haha :D

  • I'm probably a horrible person to answer since I'm not a programmer. I did some very different kind of programming a lot time ago that was nothing like this.

    Anyway, it looks like a rounding issue. Do you need to declare the precision, or rounding or anything? Maybe when you define the variable?

  • I would start by debugging your code, make sure that all variable up to the last one contain the values that they should. If not then there is your problem. If the do then it's something mathematically wring in your final assignment statement

    What language is this? C#?

    • I made sure they all contain the values they should, still the same problem
      I'm using java

    • Its in java

    • Ahh i'm not really a java programmer, i've double checked your figures and they are correct, so that leaves me to conclude it's the last assignment statement thats wrong. What happens if you hard code in the values into the parameters rather than assigning them via maths. That way you can tell if it's a logic problem or if it's something maths related

What Girls Said 0

Be the first girl to share an opinion
and earn 1 more Xper point!