HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Calculate volume of a cylinder with user input

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
cylinderwithuserinputcalculatevolume

Problem

I'm looking for a fast OR simple way to calculate the volume of a user-entered cylinder. Here is my solution:

#include 
using namespace std;
#include 

int main()
{
    long double pi = acos(-1);
    cout.precision(1000);
    long double radius;
    long double volume;
    long double height;
    cout > radius;
    long double radius_sq = radius * radius;
    cout > height;
    volume = pi * radius_sq * height;
    cout << endl << "The cylinder's volume is " << volume << "." << endl;
    return 0;
}


It's obvious to see that I'm a new programmer from the way I wrote this....which is why I want to learn from your remarks.

Solution

Your implementation is quite simple,
but a bit hard to read:

  • It's a wall of code, with no vertical spacing to visual separate closely related groups



  • The ordering of statements is haphazard, with no discernible underlying logic



Consider this alternative:

#include 
#include 

long double calculateCylinderVolume(long double radius, long double height)
{
    return acos(-1) * radius * radius * height;
}

int main()
{
    std::cout > radius;

    std::cout > height;

    std::cout.precision(1000);
    std::cout << "\nThe cylinder's volume is "
        << calculateCylinderVolume(radius, height) << ".\n";
}


Notice that:

  • variables are not declared sooner than really needed



  • the std::cout.precision(1000); is delayed until it's actually needed



  • the blank lines visually separate the closely related statements, improving readability



Other minor improvements:

  • using namespace std is considered bad practice



  • return 0 at the end of main is unnecessary



  • \n is more efficient than std::endl



  • #include instead of #include , as pointed out by @FredLarson

Code Snippets

#include <iostream>
#include <cmath>

long double calculateCylinderVolume(long double radius, long double height)
{
    return acos(-1) * radius * radius * height;
}

int main()
{
    std::cout << "Hello to the cylinder volume solver!\n";

    std::cout << "Please enter the cylinder's radius: ";
    long double radius;
    std::cin >> radius;

    std::cout << "\nPlease enter the cylinder's height: ";
    long double height;
    std::cin >> height;

    std::cout.precision(1000);
    std::cout << "\nThe cylinder's volume is "
        << calculateCylinderVolume(radius, height) << ".\n";
}

Context

StackExchange Code Review Q#115277, answer score: 8

Revisions (0)

No revisions yet.