我的代碼允許用戶輸入一些數字或從文檔中讀取它們。我怎麼也讓用戶從數學問題的選擇中挑選出來,而不用在我的主要代碼中使用一堆代碼來執行這些數字。 這裏是我到目前爲止的代碼:我會如何選擇做多個數學問題而不必每次都複製和粘貼代碼?
#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;
}
所以你問如何將代碼移出'main()'函數和其他結構?你在找什麼東西,比如'methods'和'classes'。 – David
如果您複製代碼,請將複製的代碼移到單獨的函數中。調用該函數而不是重複代碼。 – Peter