L oop не ломается сразу - PullRequest
       29

L oop не ломается сразу

0 голосов
/ 29 марта 2020

У меня есть do-while l oop, который должен остановиться, если будет введено что-либо, кроме чисел 1, 2, 3 или 4, но я получу бесконечное l oop, если уберу cin >> choicenum условие из условия l oop или программа останавливается. Как это исправить, чтобы программа автоматически возвращалась к выбору?

#include <iostream>
#include <fstream>
#include <cmath>
#include <limits>
using namespace std;

int choicenum;
float num3, num4, num5, num6, num7, num8, conerslt, sphererslt, octrslt, distrslt, FindVolCone (float, float), num1, num2; 
float FindVolSphere (float), FindAreaOct (float), Finddisttwopoint (float, float, float, float);
void dispVolCone (float, float, float), dispVolSphere (float, float), dispAreaOct (float, float), dispdisttwopoint (float, float, float, float, float);
const long double PI = acos(-1);

int main()
{

    do
    {
         // Give the user their options
        cout << "This program can calculate the following things: " << endl;
        cout << "The volume of a cone, " << endl;
        cout << "The volume of a sphere, " << endl;
        cout << "The area of an octagon, " << endl;
        cout << "Or the distance between two points. " << endl;
        // Prompt the user to make a choice
        cout << "For the volume of a cone, please enter the number 1. " << endl << "For the volume of a sphere, please enter 2. " << endl;
        cout << "For the area of an octagon, please enter 3. " << endl << "For the distance between two points, please enter 4. " << endl;
        cout << "If you would like to close this program, enter any other key." << endl;
        cin >> choicenum;

        switch (choicenum)
        {
            case 1: 
                cout << "Please enter the radius of the cone: " << endl;
                cin >> num1;
                cout << "Please enter the height of the cone: " << endl;
                cin >> num2;
                conerslt = FindVolCone (num1, num2);

                dispVolCone (num1, num2, conerslt);

                break;          
            case 2: // Calculate volume of sphere;
                cout << "Please enter the radius of the sphere: " << endl;
                cin >> num3;
                sphererslt = FindVolSphere (num3);

                dispVolSphere (num3, sphererslt);

                break;      
            case 3: // Calculate area of octagon;
                cout << "Please enter one side of the octagon: " << endl;
                cin >> num4;
                octrslt = FindAreaOct (num4);

                dispAreaOct (num4, octrslt);

                break;          
            case 4: // Calculate distance between two points;
                cout << "Please enter the x value, then y value of the first point: " << endl;
                cin >> num5;
                cin >> num6;
                cout << "Please enter the x value, then y value of the second point: " << endl;
                cin >> num7;
                cin >> num8;
                distrslt = Finddisttwopoint (num5, num6, num7, num8);

                dispdisttwopoint (num5, num6, num7, num8, distrslt);

                break;          
            default: // Kill program;
                cout << "Thank you for using this program. " << endl;
                break;
        } 


    } while (cin >> choicenum && choicenum >= 1, choicenum <= 4);

    return 0;
}

float FindVolCone (float radnumcone, float heightnumcone)
{
    float VolCone;
    VolCone = PI * pow(radnumcone, 2) * (heightnumcone / 3);
    return VolCone;
}

void dispVolCone (float radnumcone, float heightnumcone, float VolCone)
{
    cout << "The volume of a cone with radius " << radnumcone << " and height " << heightnumcone << " is " << VolCone << ". " << endl;

}

float FindVolSphere (float radnumsphere)
{
    float VolSphere;
    VolSphere = (4 / 3) * PI * pow(radnumsphere, 3);
    return VolSphere;
}

void dispVolSphere (float radnumsphere, float VolSphere)
{
    cout << "The volume of a sphere with radius " << radnumsphere << " is " << VolSphere << ". " << endl;

}

float FindAreaOct (float sidenumoct)
{
    float AreaOct;
    AreaOct = 2 * (1 + sqrt(2)) * pow(sidenumoct,2);
    return AreaOct;
}

void dispAreaOct (float sidenumoct, float AreaOct)
{
    cout << "The area of an octagon with side length " << sidenumoct << " is " << AreaOct << ". " << endl;

}

float Finddisttwopoint (float xvalone, float yvalone, float xvaltwo, float yvaltwo)
{
    float disttwopoint;
    disttwopoint = sqrt(pow((xvaltwo - xvalone),2) + pow((yvaltwo - yvalone),2));
    return disttwopoint;
}

void dispdisttwopoint (float xvalone, float yvalone, float xvaltwo, float yvaltwo, float disttwopoint)
{
    cout << "The distance between point (" << xvalone << ", " << yvalone << ") and (" << xvaltwo << ", " << yvaltwo << ") is " << disttwopoint << ". " << endl;
}                 

1 Ответ

0 голосов
/ 29 марта 2020

у вас есть опечатка в:

cin >> choicenum && choicenum> = 1, choicenum <= 4 </p>

должно быть

cin >> choicenum && choicenum >= 1 && choicenum <= 4

значение a, b, ..., c является значением c

Но вы перечитаете снова choicenum в начале l oop Вы уверены, что хотите этого?

Также в:

   default: // Kill program;
   cout << "Thank you for using this program. " << endl;
   break;

перерыв не позволяет выйти из do - в то время как , учитывая, что функция ничего не делает после l oop, вы можете заменить break на return 0 и заменить do-while для (;;) :

int main()
{
  for(;;)
  {
    // Give the user their options
    cout << "This program can calculate the following things: " << endl;
    ...
    int choicenum;

    if (!(cin >> choicenum))
      // not a number, will finish as a number out of 1..4
      choicenum = 0;

    switch (choicenum)
    {
       case 1: 
         ...
       break;        
       case 2: // Calculate volume of sphere;
         ...
       break;     
       case 3: // Calculate area of octagon;
         ...
       break;        
       case 4: // Calculate distance between two points;
         ...
       break;
       default: // Kill program;
         cout << "Thank you for using this program. " << endl;
         return 0;
    }
} 

Я добавил локальную переменную choicenum и управляю случаем, когда пользователь не вводит действительный int * От 1039 * до конечных sh в этом случае.

Я рекомендую также использовать локальные переменные для num3, num4, num5, ...

...