如何使用交换机提出问题并根据用户从交换机中选择的内容获得最终解决方案?

时间:2014-12-15 18:44:10

标签: c++ switch-statement

所以我想这样做。我有一个运行开关的程序。从开关您可以选择1,2,3或4,每个选择都是一个形状。输入必要的条目以计算所述形状的面积。我完成了其中的所有4个。

现在,交换机的最后部分需要采取用户选择的内容并计算总面积。我无法弄清楚如何只在交换机的最后部分包含用户选择。

我的意思是,如果用户选择了圆形,而是三角形而不是矩形或正方形。如何让最终开关知道用户只选择了三角形和圆形而不是其他两个?

修改

好的,我现在改了。这是我更新的代码。目前正在遇到这个问题。它计算了一切,但我的if else声明。

EDIT2: 解决。

我遇到的问题(如果有人遇到过这个问题,我希望大多数人不会),我必须在每个案例中添加choices.push_back(2);,然后向量在if案例5中的if循环中正确调用它。

 

using namespace std; double SLength, SWidth, SArea, RLength, RWidth, RArea, radius, CArea, base, height, TArea, total_area, labor, carpet, total, taxcost; const double pi = 3.14; const double cost = 2.45; const double tax = .085; vector<int> choices; void AreaSquare() //creating an equation to be called to in my switch for fahrenheit conversion { SArea = pow(SLength,2.0); } void AreaRectangle() //creating an equation to be called to in my switch for fahrenheit conversion { RArea = (RWidth * RLength); } void AreaCircle() //creating an equation to be called to in my switch for fahrenheit conversion { CArea = pi * pow(radius,2.0); } void AreaTriangle() //creating an equation to be called to in my switch for fahrenheit conversion { TArea = 0.5 * base * height; } int main() { unsigned short choice; do { cout << "Please choose from the following: " << "\n"; cout << "1: Square"<< "\n"; cout << "2: Rectangle"<< "\n"; cout << "3: Circle"<< "\n"; cout << "4: Triangle"<< "\n"; cout << "5: Total Area"<< "\n"; cout << "0: To Exit the Program"<< "\n"; cin >> choice; system ("cls"); switch (choice) { case 1: cout << "Please enter the Length: "; cin >> SLength; AreaSquare(); cout << "The area of the Square is " << SArea << "\n"; total_area += SArea; system ("pause"); // pauses the program system ("cls"); //clears the screen break; case 2: cout << "Please enter the Length: "; cin >> RLength; cout << "Please enter the Width: "; cin >> RWidth; AreaRectangle(); cout << "The area of the Rectangle is " << RArea<< "\n"; total_area += RArea; system ("pause"); // pauses the program system ("cls"); //clears the screen break; case 3: cout << "Please enter the Radius of the Circle: "; cin >> radius; AreaCircle(); cout << "The area of the Circle is: " << CArea<< "\n"; total_area += CArea; system ("pause"); // pauses the program system ("cls"); //clears the screen break; case 4: cout << "Please enter the base of the Triangle: "; cin >> base; cout << "Please enter the height of the Triangle: "; cin >> height; AreaTriangle(); cout << "The area of the Triangle is " << TArea << "\n"; total_area += TArea; system ("pause"); // pauses the program system ("cls"); //clears the screen break; case 5: for ( size_t i = 0; i < choices.size(); i++ ) { if ( choices[i] == 1 ) { cout << "Shape: Square" << "\n"; cout << "Length: " << SLength << "\n"; cout << "Area: " << SArea << "Square Feet" << "\n"; } else if ( choices[i] == 2 ) { cout << "Shape: Rectangle" << "\n"; cout << "Length: " << RLength << "\n"; cout << "Width: " << RWidth << "\n"; cout << "Area: " << RArea << "Square Feet"<< "\n"; } else if ( choices[i] == 3 ) { cout << "Shape: Circle" << "\n"; cout << "Radius: " << radius << "\n"; cout << "Area: " << CArea << "Square Feet" << "\n"; } else if ( choices[i] == 4 ) { cout << "Shape: Triangle" << "\n"; cout << "Base: " << base << "\n"; cout << "Height: " << height << "\n"; cout << "Area: " << TArea << "Square Feet" << "\n"; } } labor = (total_area / 50) * 35.72; carpet = (total_area * 2.45); taxcost = (labor + carpet) * tax; total = (labor + carpet + taxcost) ; cout << fixed << showpoint << setprecision(2); cout << "Total area: $" << total_area << " Square Feet " << "\n"; cout << "Carpet Cost: $" << carpet << "\n"; cout << "Labor cost: $" << labor << "\n"; cout << "Tax: $" << taxcost << "\n"; cout << "Total Cost: $" << total << "\n"; case 0: //case in case user selects 0 the program will exit cout << "Program is terminating..."<< endl; system ("pause"); return 0; break; //causes the prgram to execute the next statement outside the switch default: //the third case incase the user enters an invalid option cout << "That is not an option!" << endl; cout << "Please try again." << endl; cout << "\n" << endl; cout << "\n" << endl; cout << "\n" << endl; system ("pause"); // pauses the program system ("cls"); //clears the screen break; //causes the program to execute the next statement outside the switch } } while (choice != 0); }

3 个答案:

答案 0 :(得分:0)

由于所有area *变量都是全局变量,因此默认情况下它们初始化为0。所以最简单的方法是添加所有区域*变量。

我可以告诉你正在学习编程,所以我只是说这个课程有很大的改进空间。

答案 1 :(得分:0)

您需要存储它们。你知道矢量吗?

std::vector<int> choices;

然后,在每个案例中:,执行此操作:

choices.push_back( n ); // where n = the input

仅在您需要确切知道所选内容和次数时才需要这样做。如果您只需要总面积,只需将总面积存储在具有适当范围的变量(如选项)中,并在每次迭代时附加每个形状的区域。

编辑:

好的,有几种方法可以做到这一点。使用您给定的代码库,我认为最简单的方法是在每种情况下将总面积存储在变量中,并将每个选项存储在一个向量中(参见上文)。在案例5:中,您需要循环遍历该向量并显示所有先前的选项,并在该循环之外打印总区域。

case 5:
for ( size_t i = 0; i < choices.size(); i++ ) {
      if ( choices[i] == 0 ) {
           // print out shape associated w/ zero
      } else if ( choice[i] == 1 ) {
           // print out shape associated w/ 1
      }
      //... etc.
 }

 std::cout << "Total area: " << total_area << std:::endl;

答案 2 :(得分:0)

你有很多问题。首先,你的程序的当前状态,即使没有你想要的额外位,已经破坏了缺少break语句和复制粘贴错误。我现在很累,很痛苦,所以也许我稍后会解释,但这是你程序的清理版本。总结是你不需要全局变量,如果你在交换机中的多个案例中重复某些事情,那么可能应该在交换机之外完成某些事情,具有有意义名称的枚举使得更容易分辨出你正在做什么而不是文字,for循环存在,所以你不必重复相同的代码六次,你只需要一个return语句,没有人真正使用do-while循环,如果你可以控制起始条件,你可以缓存区域结果一个额外的变量。

编辑:我没有意识到除了总面积之外你还想存储形状选择,所以我添加了一个std :: vector,它是一个动态数组,用于存储用户选择.I'故意遗漏存储宽度,高度,半径等,原因有两个:1)现在你已经看到我如何存储选择,你应该能够用你想要存储的任何东西复制那个逻辑,并且2)通过程序编程就像你在这里所做的那样,它的工作量超过它的价值。相反,在这一点上开始学习结构和类是更明智的。

#include <iostream>
#include <vector>

using namespace std;
const double pi = 3.14;

enum Option
{
    Exit=0,
    Square,
    Rectangle,
    Circle,
    Triangle,
    Totals,
    Max
};
const char* const OptionNames[Max] =
{
    "Exit",
    "Square",
    "Rectangle",
    "Circle",
    "Triangle",
    "Total Area"
};

int main()
{
    // Declare a container to store user selections in
    vector<Option> selections;

    // Declare a variable that stores the total area
    double areaTotal = 0;

    // Declare a variable to store the user's input and initialize it to something other than the exit condition
    int userChoice = Totals;

    // While the user hasn't opted to exit
    while (Exit != userChoice)
    {
        // Prompt the user to select a shape
        cout << "Please select a shape:\n";

        // Iterate over all options, starting with square, and display their corresponding names
        for (int i=Square; i<Max; ++i)
        {
            cout << i << ". " << OptionNames[i] << '\n';
        }

        // Show the Exit option last
        cout << Exit << ". " << OptionNames[Exit] << '\n';

        // Take the user's input
        cin >> userChoice;

        // If they entered a shape (not Exit or Total), save their selection
        if (userChoice > Exit && userChoice < Totals)
            selections.push_back(Option(userChoice));   // cast the int to an Option

        // Evaluate the selection
        switch (userChoice)
        {
            case Exit:
            { 
                cout << "Program is terminating...\n";
                break;
                // Nothing else needs to be done here, as we are breaking out of the switch, and the while-loop's exit condition is now met
            }
            case Square:
            {
                cout << "Please enter the length of one side: ";
                double length;
                cin >> length;

                double area = length * length;
                cout << "The area of the Square is " << area << '\n';
                areaTotal += area;

                break;
            }
            case Rectangle:
            {
                cout << "Please enter the length: ";
                double length;
                cin >> length;

                cout << "Please enter the width: ";
                double width;
                cin >> width;

                double area = (length * width);
                cout << "The area of the Rectangle is " << area << '\n';
                areaTotal += area;

                break;
            }
            case Circle:
            {
                cout << "Please enter the radius: ";
                double radius;
                cin >> radius;

                double area = pi * pow(radius, 2.0);
                cout << "The area of the Circle is: " << area << '\n';
                areaTotal += area;

                break;
            }
            case Triangle:
            {
                cout << "Please enter the base: ";
                double base;
                cin >> base;

                cout << "Please enter the hight: ";
                double height;
                cin >> height;

                double area = 0.5 * base * height;
                cout << "The area of the triangle is " << area << '\n';
                areaTotal += area;

                break;
            }
            case Totals:
            {
                cout << "Your selections were:\n";

                // Iterate over all selections except the last one, placing a comma and space after each one
                int i;
                for (i=0; i<selections.size()-1; ++i)
                {
                    cout << OptionNames[selections[i]] << ", ";
                }
                // The last selection goes outside the for-loop, so we can put a newline after it instead of a comma
                cout << OptionNames[selections[i]] << ".\n";

                // Display the total area
                cout << "The total area is: " << areaTotal << '\n';
                break;
            }
            default:
            {
                cout << "That is not an option!\n";
                cout << "Please try again.\n";
                break;
            }
        }
    }

    system("pause");

    return 0;
}