Volume of a Cylinder. The result is off by one decimal point.

I need to write a program to compute the Volume of a Cylinder by Repeated Addition.

This is what I got so far:

double radius, hight, volume, pi = 3.1416, x, y, z;

Scanner keyboard = new Scanner (System.in);

System.out.println("Enter the radius: ");
radius = keyboard.nextDouble ();

System.out.println("Enter the hight: ");
hight = keyboard.nextDouble ();

x=0;
for (int i=0; i<radius; i++)
x+=radius;

y=0;
for (int j=0 ; j<hight;j++)
y+= hight;

z=0;
for (int k=0; k<y ; k++)
z+=pi;

volume = z;
System.out.println("The volume is: " + volume);

When I run the program The result is off by one decimal point.

Ex: radius = 10, hight = 10
Result will come back as 314.16 when it should be 3141.6

I'm stuck and do not know how to solve this issue.
Doesn't look like C or C++ :)

But anyway the algorithm looks wrong. What use is made of the value of variable x ?

Also, since the loops can iterate only a whole number of times, several of the variables should be of integer type.
Last edited on
This just so happened to turn out this way because you used two equal values being 10. If you would have used lets say 18 & 34, then it would probably have been much more evident.

In any case;

1
2
3
    z = 0;
    for ( int k = 0; k < y; k++ )
        z += pi;

y is not including x and that is why your off by one decimal.

Enclosing code with code tags
would have been easier to point out error by line number.
Topic archived. No new replies allowed.