计算飞行距离的程序

时间:2014-03-02 21:18:25

标签: c++ void

我在使用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;
    }

1 个答案:

答案 0 :(得分:3)

要通过reference-parameter从void函数返回一个值,变量必须存在于调用者的作用域中,作为参数。

因此,在您的情况下,例如要调用askDataSet,首先必须声明int来保存结果:

int w;
askDataSet(w);

然后askDataSet将写入您的整数变量,您可以在调用后使用它。

我注意到代码的其他要点:

  • 对于readFile调用,传递的变量必须与参数类型相同(double,而不是int)。
  • readData来电之前的声明中有一个额外的逗号:“lat3, , lon1
  • 也许您想要用beginLatmidLon(或其他方式)替换lat1lon2等。
  • readFile似乎有一个未使用的第一个参数int wall1readFile中缺少该参数main
  • dist函数未定义,在main结束时,您尝试打印它。
  • 要使用systemexit,您应该#include <cstdlib>