2017-03-03 20 views
-2

我的代碼允許用戶輸入一些數字或從文檔中讀取它們。我怎麼也讓用戶從數學問題的選擇中挑選出來,而不用在我的主要代碼中使用一堆代碼來執行這些數字。 這裏是我到目前爲止的代碼:我會如何選擇做多個數學問題而不必每次都複製和粘貼代碼?

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

所以你問如何將代碼移出'main()'函數和其他結構?你在找什麼東西,比如'methods'和'classes'。 – David

+0

如果您複製代碼,請將複製的代碼移到單獨的函數中。調用該函數而不是重複代碼。 – Peter

回答

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

+0

常用的技術是使用'switch'來處理菜單項,而不是'if-else'階梯。 –

+0

兄弟第一次我要重溫他使用一些適當的方式和設計模式,並結束複製他的代碼。 –