我将如何选择进行多个数学问题,而无需每次复制和粘贴代码

How would I give the choice to do multiple math problems without having to copy and paste the code each time?

本文关键字:问题 代码 复制 何选择 选择      更新时间:2023-10-16

我的代码允许用户输入一些数字或从文档中读取它们。我还将如何允许用户从选择数学问题的选择中挑选这些数字,而无需在我的主体中有一堆代码。到目前为止,这是我的代码:

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

可能是您可以尝试这样的事情:

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

choice1包含int [...] list.push_back(x);}时等...