2014-03-02 53 views
0

我在使用void函数的程序遇到问题。我以前从未使用过,所以我有点迷路。我的计划有3套城市。它应该把三个城市放在其中一个集合中,并计算出该航班的时间。我的问题是,我不断收到我的变量未定义的错误。这是我尝试使用void函数的第一个程序。我尝试过自己初始化每个变量,但我认为这不是正确的方法或是它吗?任何帮助,将不胜感激。这是我的代码:计算飞行距离的程序

#include <fstream> 
#include <iostream> 
#include <string> 

using namespace std; 
void readFile (int wall1, double &lat1, double &lon1, string &city1, 
         double &lat2, double &lon2, string &city2, 
         double &lat3, double &lon3, string &city3); 
void intro(); 
void askDataSet(int &w); 

//-------------------------------------------------- 
int main() 
{ 

    intro(); 
    askDataSet(int &w); 
    string name; 


    int lat1, lat2, lat3, , lon1, lon2, lon3, beginLat, beginLon, beginCity, midLat, midLon, midCity, endLat, endLon, endCity; 
    string city1, city2, city3; 
    readFile (beginLat, beginLon, beginCity, midLat, midLon, midCity, endLat, endLon, endCity); 
    cout << "The First City at coordinates " << beginLat << " and " << lon1 << " is: " << city1 << endl; 
    cout << "The Second City is at coordinates " << beginLat << " is " << lon2 << ": " << city2 << endl; 
    cout << "The Third City is at coordinates " << beginLat << " is " << lon3 << ": " << city3 << endl; 

    leg1 = dist(beginLat, beginLon, midLat, midLon); 
    leg2 = dist(midLat, midLon, endLat, endLon); 
    nonstop = dist(leg1-leg2); 

    cout << "It is " << dist << "fewer miles for non-stop" << endl; 


    system("pause"); 
    return 0; 
} 

void readFile (int &wall1, double &lat1, double &lon1, string &city1, 
       double &lat2, double &lon2, string &city2, 
       double &lat3, double &lon3, string &city3) 
{ 
    ifstream dataIn; 
    dataIn.open("cities.txt"); 
    if(dataIn.fail()) 
{ 
    cout << "Error. File does not exist. " << endl; 
    exit(1); 
} 

    dataIn >> lat1; 
    dataIn >> lon1; 
    dataIn.get(); 
    getline(dataIn, city1); 
    dataIn >> lat2; 
    dataIn >> lon2; 
    dataIn.get(); 
    getline(dataIn, city2); 
    dataIn >> lat3; 
    dataIn >> lon3; 
    dataIn.get(); 
    getline(dataIn, city3); 

} 

    void intro() 
    { 
    cout << "In this lab we will try to figure out how much shorter it is to fly non-stop compared to one-stop." << endl; 
    cout << endl; 
    } 

    void askDataSet(int &w) 
    { 
    cout << "Which set of cities would you like to figure the distances for? " << endl; 
    cin >> w; 
    } 
+2

请缩进您的代码。你会发现它对你也有帮助。那么你的意思是什么呢?如果像这样的'void intro();'和下面的对象,它被称为函数 – deviantfan

+0

你应该*给* askDataSet一个'int&'。 – chris

回答

3

要通过参考参数给回从空隙函数的值,变量具有其中给出为参数的呼叫者的范围存在。

你的情况

因此,例如打电话askDataSet,你首先要申报int容纳结果:

int w; 
askDataSet(w); 

然后askDataSet将写入您的整型变量,而您可以在呼叫后再使用。

进一步指出我的代码注意到:

  • 对于readFile调用,通过必须具有相同类型的参数(double,不int)的变量。
  • 有一个在readData调用之前的声明一个额外的逗号:“lat3, , lon1
  • 也许你会想取代beginLatmidLon等与lat1lon2(或者反过来)。
  • readFile似乎有一个未使用的第一个参数int wall1,在mainreadFile -all中没有。
  • dist函数未定义,并且在main的末尾尝试打印它。
  • 要使用systemexit,您应该#include <cstdlib>