Volume of a sphere, loop for diff radii

I am trying to write a program that will find the volume of a sphere, and prints the volume for radii from 0.0 to 4.0 in increments of 0.2.

so that it reads out:
radius: 0.00 volume: 0.000
radius: 0.20 volume: 0.033
radius: 0.40 volume: 0.268
..........
radius: 4.00 volume: 268.08


I got the formula and all that, having trouble on how to tell the loop to go in .2 increments.
Have any code?
as of right now, just the basic code to to set up the equation. nothing with the loop sequence, because i cant figure it out.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
#define PI 3.1415926

int main()
{
    float V, r;
      V = (4/3 * PI * r * r * r);       
    system ("pause");
    return 0;   
}
Last edited on
The math library has M_PI defined in it, so #include <math>, then use M_PI where ever you need it.

Always initialise your variables, preferably when you declare them, comment what the variable means

1
2
3
4
5
float fVolume = 0.0;      //The Volume of the sphere
float fRadius = 0.0        //the radius;


//set the variables to the values you want down here. 

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
#define PI 3.1415926

int main()
{
  for (double r=0.0;r<=4.0;r=r+0.2) {
       cout<<"radius:"<<r<<"  volume:"<<(4/3 * PI * r * r * r)<<endl;   
  }    
   system ("pause");
   return 0;   
}
Last edited on
ok thank you.

what does "double" do in line 7, gelatine?
for (double r=0.0;r<=4.0;r=r+0.2)

didn't know you could do that, thought they had to be integer types (I might be wrong)

also to be careful comparing floats.

Edit : r <=4.0 could fail when r is 4.0 because of the float type.
Last edited on
Topic archived. No new replies allowed.