在下面用C ++简化我的代码

时间:2018-02-20 03:35:57

标签: c++ function formula block

我想创建一个能够计算表面积,体积和周长的程序。对于你的其他信息,我正在研究函数,我刚刚学习了一周的C ++。

#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;
}

也许你们中的一个想要重写并添加一些注释,哪些部分能够简化,所以我可以更容易理解。

1 个答案:

答案 0 :(得分:0)

首先,看起来您应该将所有整数输入变为double而不是int,因为它预计您的输入不一定是一个确切的整数(可能)。您还可以删除所有重复功能以输入参数。将其更改为单个函数,并为每个变量调用一个函数。

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;
}