C/C++ What is the equation for computing the volume of a sphere using C++?

  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    C++ Sphere Volume
Click For Summary
To compute the volume of a sphere given the radius and the value of pi, the correct formula is (4.0 / 3.0) * pi * r^3. It's crucial to use floating-point division with 4.0 and 3.0 instead of integer division with 4 and 3. The volume should be calculated using repeated multiplication for r^3, as the provided code does not include the cmath library for the power function. The correct assignment for sphereVolume is sphereVolume = (4.0 / 3.0) * piVal * (sphereRadius * sphereRadius * sphereRadius). This ensures accurate volume calculation in cubic meters, not square meters.
ineedhelpnow
Messages
649
Reaction score
0
Given sphereRadius and piVal, compute the volume of a sphere and assign to sphereVolume. Look up the equation online. Use (4.0 / 3.0) to perform floating-point division, instead of (4 / 3) which performs integer division.

Sample program:

#include <iostream>
using namespace std;

int main() {
const double piVal = 3.14159;
double sphereVolume = 0.0;
double sphereRadius = 0.0;

sphereRadius = 1.0;
<STUDENT CODE>
cout << "Sphere volume: " << sphereVolume << endl;

return 0;

ive tried EVERYTHING for this but i still can't figure out how to compute the volume. equation for the volume of a sphere is $\frac{4}{3} \pi r^2$. oh and instead of 4 and 3 i have to use 4.0 and 3.0.
 
Technology news on Phys.org
ineedhelpnow said:
equation for the volume of a sphere is $\frac{4}{3} \pi r^2$.
Volume is measured in meters cubed, not meters squared.

Hint: There is a tag [CODE]...[/CODE] designed specifically for code segments. It provides monospaced font and preserves alignment.
 
oops i missed that. I am still not getting it right though.
 
ineedhelpnow said:
im still not getting it right though.
What code line do you propose? Remember to use sphereRadius and piVal, not their values. Also, use repeated multiplication to compute $r^3$. In order to use the built-in power function, you need to include the cmath file, which the code you've been given does not do.
 
oh thank u thank u thank u thank u thank u! i was doing sphereVolume = (4.0 / 3.0) * piVal * (sphereRadius ^3);

instead of sphereVolume = (4.0 / 3.0) * piVal * (sphereRadius * sphereRadius * sphereRadius)
 

Similar threads