Search code examples
c++functionformulablock

simplify my code in C++ below


I want to create a program which is able to calculate the surface area, volume, and circumference. for your additional info, I am studying about function, I has just learned about C++ about a week.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int getPostP(string msgP)
{
    int Ppost= 0.000;

    do
    {
        cout << msgP << endl;
        cin >> Ppost;

        return Ppost;
    } while(Ppost<= 0);
}

int getPostL(string msgL)
{
    int Lpost= 0.000;

    do
    {
        cout << msgL << endl;
        cin >> Lpost;

        return Lpost;
    } while(Lpost<= 0);
}

int getPostT(string msgT)
{
    int Tpost = 0.000;

    do
    {
        cout << msgT << endl;
        cin >> Tpost;

        return Tpost;
    } while(Tpost <= 0);
}

int surfaceArea(int Psur, int Lsur, int Tsur)
{
    return (2*Psur*Lsur)+(2*Psur*Tsur)+(2*Lsur*Tsur);
}

int volume(int Pvol, int Lvol, int Tvol)
{
    return (Pvol*Lvol*Tvol);
}

float circumference(int Pcir, int Lcir, int Tcir)
{
    return 4*(Pcir+Lcir+Tcir);
}

int main()
{
    int P = getPostP("enter the P of your block");
    int L = getPostL("enter the L of your block");
    int T = getPostT("enter the T of your block");


    float surfAreaBlock = surfaceArea(P, L, T);

    float volBlock = volume(P, L, T);

    float cirBlock = circumference(P, L, T);

    cout << "block which have P = " << P << " and L = " << L << " and T = "<< T << " have surface area = " <<
        surfAreaBlock << " and volume = " << volBlock << " and cirBlock = " << cirBlock;

    return 0;
}

Maybe one of you want to rewrite and add some comment, which parts are able to simplify, so I can understand easier.


Solution

  • First of all, it looks like you should make all of your integer inputs into double instead of int, since it's expected that your inputs won't necessarily be an exact integer amount (probably). Also you can get rid of all of your duplicate functions for entering the parameters. Change it to a single function and call that one for each variable.

    double getInput(const std::string& prompt)
    {
        double input(0.0);
        do
        {
            std::cout << prompt << "\n-> " << std::flush;
            // forces input to be a double type
            while (!(std::cin >> input))
            {
                std::cout << "\n-> " << std::flush;
                std::cin.clear();
                std::cin.ignore(256, '\n'); ///< could use streamsize::max here
            }
        } while (input <= 0.0);  ///< make sure it's positive
        return input;
    }