Создание функции для вывода строки, когда ввод отрицательный или ноль. Первый раз выполняю пользовательские функции - PullRequest
1 голос
/ 24 февраля 2020

Я пытаюсь создать пользовательскую функцию в C ++, чтобы предотвратить бесконечный ввод l oop неправильного ввода для двойной переменной и проверку, является ли ввод отрицательным или нулевым. Если это так, функция go выполнит задание l oop, чтобы попросить пользователя повторить попытку, пока значение больше не будет чем-то иным, кроме двойного, отрицательного или нулевого.

Функция fix () определяется пользователем

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;

string fix(double x)
{
    string B_error = "B cannot be zero or negative. Please try again: ";
    string H_error = "H cannot be zero or negative. Please try again: ";
    string h_error = "b cannot be zero or negative. Please try again: ";
    string b_error = "h cannot be zero or negative. Please try again: ";
    string r_error = "r cannot be zero or negative. Please try again: ";
    string y_error;

    while (!(cin >> x))
    {
        if (cin.fail())
        {
            cout << "Erroneous input. Please try again:\n";

            cin.clear(); // used to prevent an endless loop if an input type is not an integer
            cin.ignore(10000, '\n');
        }
    }

    if (x == 'B')
        {
            y_error = B_error;


    if (x <= 0)
        {
            do 
            {
                return y_error;
                cin >> x;
            }
            while (x <= 0);
        }
}
    return 0;
}

int main()
{
int selection;
double I, B, H, b, h, r, fix(double);

cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";

while (!(cin >> selection) || selection < 1 || selection > 3)
{
    if (cin.fail() || selection < 1 || selection > 3)
    {
        cout << "Erroneous input. Please try again:\n";

        cin.clear(); // used to prevent an endless loop if an input type is not an integer
        cin.ignore(10000, '\n');
    }   
}

switch (selection)
{
    case 1:
        cout << "You have selected I-beam. All inputs must be in inches.\n"
        << "Please input the value for B: ";
        fix(B);


        cout << "Please input the value for H: ";
        fix(H);

        if (H <= 0)
        {
            do 
            {
                cout << "H cannot be zero or negative. Please try again: ";
                cin >> H;
            }
            while (H <= 0);
        }

        cout << "Please input the value for b: ";
        fix(b);

        if (b <= 0)
        {
            do 
            {
                cout << "b cannot be zero or negative. Please try again: ";
                cin >> b;
            }
            while (b <= 0);
        }

        else if (b > B)
        {
            do
            {
                cout << "b cannot be larger than B. Please try again: ";
                cin >> b;
            }
            while (b > B);
        }

        cout << "Please input the value for h: ";
        fix(h);

        if (h <= 0)
        {
            do 
            {
                cout << "h cannot be zero or negative. Please try again: ";
                cin >> h;
            }
            while (h <= 0);
        }

        else if (h > H)
        {
            do
            {
                cout << "h cannot be larger than H. Please try again: ";
                cin >> H;
            }
            while (h > H);
        }

        I = (B*H*H*H - b*h*h*h)/12.;

        cout << "\nResults for an I-beam with B = " << B
        << ", H = " << H << ", b = " << b << ", and h = " << h << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;

    case 2:
        cout << "You have selected rectangular beam. All inputs must be in inches.\n"
        << "Please input the value for b: ";
        fix(b);

        if (b <= 0)
        {
            do 
            {
                cout << "b cannot be zero or negative. Please try again: ";
                cin >> b;
            }
            while (b <= 0);
        }

        cout << "Please input the value for h: ";
        fix(h);

        if (h <= 0)
        {
            do 
            {
                cout << "h cannot be zero or negative. Please try again: ";
                cin >> h;
            }
            while (h <= 0);
        }

        I = b*h*h*h/12.;
        cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;

    case 3:     
        cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
        << "Please input the value of r: ";
        fix(r);

        if (r <= 0)
        {
            do 
            {
                cout << "r cannot be zero or negative. Please try again: ";
                cin >> r;
            }
            while (r <= 0);
        }

        I = M_PI*pow(r,4)/4.;

        cout << "\nResults for a cylindrical beam with r = " << r << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;
}


cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";

return 0;
}

Ответы [ 2 ]

1 голос
/ 25 февраля 2020

Я удалил проблемы. Вы путаете экземпляры классов с функциями. Функции не должны быть инициализированы, экземпляры должны быть, если они находятся вне класса. Я написал несколько комментариев вдоль кода. Это все еще не красиво, но по крайней мере это работает.

string FUNCTION(double) кстати. означает, что функция может или должна возвращать только «строку». Если вы ничего не возвращаете, функция написана так void FUNCTION(double). Если вы возвращаете, например, строку, вы должны написать что-то, что получает возвращаемую строку, например:

#include <iostream>
/*
std::string returning_value;
returning_value = FUNCTION(1.0);
*/
//or

std::string FUNCTION(double function_a); //prototype of the function
//you need this if you write the function underneath the main() function
//The main function is returning "return 0" so since "0" is an "int" 
//meaning main is always "int main()" btw. because it is a function,
//just not some function but the "main function" thats called by the OS

int main()
{
std::string returning_value;
double a = 0.1; //initializing with 0.1
returning_value = FUNCTION(a);
std::cout << returning_value << std::endl;

//and in both cases the function would look like:

return 0;
}

std::string FUNCTION(double function_a)
{

std::string returning_value_a = "This is a string that will be returned";

if(function_a == 0.1)
{
returning_value_a = "This is another string";
}

return returning_value_a;
}

Ваш код с наименьшим фиксированным количеством, что вы по крайней мере работали, и вы можете проверить, как получить правильный вывод, который вы хотите получить. Веселитесь :) Надеюсь, мой ответ поможет вам:)

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;

void fix(double x)
{
    string B_error = "B cannot be zero or negative. Please try again: ";
    string H_error = "H cannot be zero or negative. Please try again: ";
    string h_error = "b cannot be zero or negative. Please try again: ";
    string b_error = "h cannot be zero or negative. Please try again: ";
    string r_error = "r cannot be zero or negative. Please try again: ";
    string y_error;

    while (!(cin >> x))
    {
        if (cin.fail())
        {
            cout << "Erroneous input. Please try again:\n";

            cin.clear(); // used to prevent an endless loop if an input type is not an integer
            cin.ignore(10000, '\n');
        }
    }
//warning: comparing floating point with == or != is unsafe
    if (x == 'B')
        {
            y_error = B_error;


    if (x <= 0)
        {
            do
            {
                cin >> x;
            }
            while (x <= 0);
        }
}

}

int main()
{
int selection;
double I, B, H, b, h, r;
//You need to initialize the variables with a value
I = 1.0;
B = 1.0;
H = 1.0;
b = 1.0;
h = 1.0;
r = 1.0;
//functions don't need to be initialized, thats for Instanzes of classes
//double fix(double);

cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";

while (!(cin >> selection) || selection < 1 || selection > 3)
{
    if (cin.fail() || selection < 1 || selection > 3)
    {
        cout << "Erroneous input. Please try again:\n";

        cin.clear(); // used to prevent an endless loop if an input type is not an integer
        cin.ignore(10000, '\n');
    }
}

switch (selection)
{
    case 1:
        cout << "You have selected I-beam. All inputs must be in inches.\n"
        << "Please input the value for B: ";
        fix(B);


        cout << "Please input the value for H: ";
        fix(H);

        if (H <= 0)
        {
            do
            {
                cout << "H cannot be zero or negative. Please try again: ";
                cin >> H;
            }
            while (H <= 0);
        }

        cout << "Please input the value for b: ";
        fix(b);

        if (b <= 0)
        {
            do
            {
                cout << "b cannot be zero or negative. Please try again: ";
                cin >> b;
            }
            while (b <= 0);
        }

        else if (b > B)
        {
            do
            {
                cout << "b cannot be larger than B. Please try again: ";
                cin >> b;
            }
            while (b > B);
        }

        cout << "Please input the value for h: ";
        fix(h);

        if (h <= 0)
        {
            do
            {
                cout << "h cannot be zero or negative. Please try again: ";
                cin >> h;
            }
            while (h <= 0);
        }

        else if (h > H)
        {
            do
            {
                cout << "h cannot be larger than H. Please try again: ";
                cin >> H;
            }
            while (h > H);
        }

        I = (B*H*H*H - b*h*h*h)/12.;

        cout << "\nResults for an I-beam with B = " << B
        << ", H = " << H << ", b = " << b << ", and h = " << h << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;

    case 2:
        cout << "You have selected rectangular beam. All inputs must be in inches.\n"
        << "Please input the value for b: ";
        fix(b);

        if (b <= 0)
        {
            do
            {
                cout << "b cannot be zero or negative. Please try again: ";
                cin >> b;
            }
            while (b <= 0);
        }

        cout << "Please input the value for h: ";
        fix(h);

        if (h <= 0)
        {
            do
            {
                cout << "h cannot be zero or negative. Please try again: ";
                cin >> h;
            }
            while (h <= 0);
        }

        I = b*h*h*h/12.;
        cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;

    case 3:
        cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
        << "Please input the value of r: ";
        fix(r);

        if (r <= 0)
        {
            do
            {
                cout << "r cannot be zero or negative. Please try again: ";
                cin >> r;
            }
            while (r <= 0);
        }

        I = M_PI*pow(r,4)/4.;

        cout << "\nResults for a cylindrical beam with r = " << r << endl;
        cout << setfill('-') << setw(32) << "" << endl;
        break;
}


cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";

return 0;
}
0 голосов
/ 25 февраля 2020

Итак, мне пришлось добавить еще одну функцию, чтобы проверить, если B Вот мой код с исправлением:

#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>

using namespace std;

void fix(double &x)
{

    while (!(cin >> x))
    {
        if (cin.fail())
        {
            cout << "Erroneous input. Please try again:\n";

            cin.clear(); // used to prevent an endless loop if an input type is not a         double
            cin.ignore(10000, '\n');
        }
    }

    string return_x = "This cannot be zero or negative. Please try again: ";

    while (x <= 0)
    {
        cout << return_x << endl;
        cin >> x;
    }

}

void fix2(double &x, double &y)
{
    while (x < y)
    {
        cout << x << " cannot be less than " << y << endl;
        fix(y);
    }
}

int main()
{
    int selection;
    double I = 1.0;
    double B = 1.0;
    double H = 1.0;
    double b = 1.0;
    double h = 1.0;
    double r = 1.0;

    cout << "Please select the type of beam:\n"
         << "1) I-Beam\n"
         << "2) Rectangular Beam\n"
         << "3) Cylindrical Beam\n";

    while (!(cin >> selection) || selection < 1 || selection > 3)
    {
        if (cin.fail() || selection < 1 || selection > 3)
        {
            cout << "Erroneous input. Please try again:\n";

            cin.clear(); // used to prevent an endless loop if an input type is not an integer
            cin.ignore(10000, '\n');
        }
    }

    switch (selection)
    {
        case 1:
            cout << "You have selected I-beam. All inputs must be in inches.\n"
                    << "Please input the value for B: ";
            fix(B);

            cout << "Please input the value for H: ";
            fix(H);

            cout << "Please input the value for b: ";
            fix(b);
            fix2(B, b);

            cout << "Please input the value for h: ";
            fix(h);
            fix2(H, h);

            I = (B * H * H * H - b * h * h * h) / 12.;

            cout << "\nResults for an I-beam with B = " << B << ", H = " << H
                 << ", b = " << b << ", and h = " << h << endl;
            cout << setfill('-') << setw(32) << "" << endl;
            break;

        case 2:
            cout << "You have selected rectangular beam. All inputs must be in inches.\n"
                 << "Please input the value for b: ";
            fix(b);

            cout << "Please input the value for h: ";
            fix(h);

            I = b * h * h * h / 12.;
            cout << "\nResults for a rectangular beam with b = " << b
                    << " and h = " << h << endl;
            cout << setfill('-') << setw(32) << "" << endl;
            break;

        case 3:
            cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
                 << "Please input the value of r: ";
            fix(r);

            I = M_PI * pow(r, 4) / 4.;

            cout << "\nResults for a cylindrical beam with r = " << r << endl;
            cout << setfill('-') << setw(32) << "" << endl;
            break;
    }

    cout << "The value of the moment of inertia for this beam is: " << I
         << "in^4" << "\n\n";

    return 0;
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...