Write a c++ function to find surface area of sphere?
Write a c++ function to find surface area of sphere?
Best answer
Surface area of a sphere \(= 4\pi r^{2}\); write a C++ function that takes the radius and returns this value.
#include <iostream>
using namespace std;
float surfaceArea(float r) {
const float PI = 3.14159;
return 4 * PI * r * r;
}
int main() {
float radius;
cout << "Enter radius of the sphere: ";
cin >> radius;
cout << "Surface area = " << surfaceArea(radius) << endl;
return 0;
}The function surfaceArea() receives the radius as a parameter and returns \(4\pi r^{2}\). For \(r = 7\): \(4 \times 3.14159 \times 49 \approx 615.75\) square units.
Be careful with \(\pi\): in C/C++ the expression 22/7 uses integer division and gives 3, not 3.142. Use 22.0/7 or a decimal value like 3.14159.
Log in or create a free account to answer this question.