我在使用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;
}
答案 0 :(得分:3)
要通过reference-parameter从void函数返回一个值,变量必须存在于调用者的作用域中,作为参数。
因此,在您的情况下,例如要调用askDataSet
,首先必须声明int
来保存结果:
int w;
askDataSet(w);
然后askDataSet
将写入您的整数变量,您可以在调用后使用它。
我注意到代码的其他要点:
readFile
调用,传递的变量必须与参数类型相同(double
,而不是int
)。readData
来电之前的声明中有一个额外的逗号:“lat3, , lon1
”beginLat
,midLon
(或其他方式)替换lat1
,lon2
等。readFile
似乎有一个未使用的第一个参数int wall1
,readFile
中缺少该参数main
。dist
函数未定义,在main
结束时,您尝试打印它。system
和exit
,您应该#include <cstdlib>
。