C++ 我如何选择做多项数学题而不必每次都复制和粘贴代码?

C++ 我如何选择做多项数学题而不必每次都复制和粘贴代码?,c++,C++,我的代码允许用户输入一些数字或从文档中读取它们。我如何允许用户从一系列数学问题中进行选择,以对这些数字执行操作,而不必在我的主程序中使用大量代码。 以下是我目前的代码: #include <iostream> #include <cmath> #include <vector> #include <fstream> #include <string> using namespace std; int main() { //as

我的代码允许用户输入一些数字或从文档中读取它们。我如何允许用户从一系列数学问题中进行选择,以对这些数字执行操作,而不必在我的主程序中使用大量代码。 以下是我目前的代码:

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

int main()
{
    //ask for file input or manual input
    cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
    int choice;
    cin >> choice;

    if (choice == 1)
    {
        int numberswanted;
        cout << "How many numbers would you like to enter?" << "\n";
        cin >> numberswanted;

        vector<double> list;
        for (int i = 0; i < numberswanted; i++)
        {
            cout << "Enter your numbers: " << "\n";
            double x;
            cin >> x;
            list.push_back(x);
        }

    }
    else if (choice == 2)
    {
        ifstream doc;
        float output;
        doc.open("input.txt");
        while (!doc.eof())
        {
            vector<double> list;
            double x;
            doc >> x;
            list.push_back(x);
        }
        doc.close();

    }
    return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
//请求文件输入或手动输入
不能选择;
如果(选项==1)
{
需要整数;
想要多少;
向量表;
for(int i=0;i>x;
列表。推回(x);
}
doc.close();
}
返回0;
}

可能您可以尝试以下方法:

int main() { cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
int choice;
cin >> choice;

if (choice == 1)
{
    choice1();

}
else if (choice == 2)
{
    choice2();

}
return 0;}
intmain(){cout-choice;
如果(选项==1)
{
选择1();
}
else if(选项==2)
{
选择2();
}
返回0;}
choice1
包含
int[…]列表时。向后推(x);}

等等。

那么您要问的是如何将代码移出
main()
函数并移到其他结构中?您要查找的是
方法
。如果要复制代码,请将复制的代码移动到单独的函数中。调用该函数,而不是复制代码。常用的技巧是使用
开关
来处理菜单项,而不是使用
if-else
梯形图。dude在第一次我建议他使用一些正确的方法和设计模式,并结束了复制他的代码。