0
int getNumAccidents(string );
void findLowest(double , double , double , double , double);

int main()
{
    string regName;
    double north = 0;
    double south = 0;
    double east = 0;
    double west = 0;
    double central = 0;
    double lowest;


    regName = "North";
    north = getNumAccidents(regName);
    regName = "South";
    south = getNumAccidents(regName);
    regName = "East";
    east = getNumAccidents(regName);
    regName = "West";
    west = getNumAccidents(regName);
    regName = "Central";
    central = getNumAccidents(regName);


    findLowest(north, south, east, west, central);

    return 0;
}

getNumAccidents 函数允许用户输入每个地区报告的事故数量。

int getNumAccidents(string regionName) 
{   
    double number;

    cout << "\nEnter number of accidents for " << regionName << " area: " << endl;
    cin >> number;

    while (number <= -1)
    {
        cout << "\nEnter a positive number: " << endl;
        cin >> number;

    }

    //cout << "Region: " << regionName << " Number: " << number << endl;

    return number;
}

findLowest 函数确定哪个地区的事故数量最少以及该地区的名称。但是如何让它显示事故数量最少的地区名称呢?

void findLowest(double n, double s, double e, double w, double c) 
{
    double lowest = n;

    if (s < lowest)
    {
        lowest = s;

    }
    if (e < lowest)
    {   
            lowest = e;

    }
    if (w < lowest)
    {
        lowest = w;

    }
    if (c < lowest)
    {
        lowest = c;

    }

    cout << "\nThe least number of accidents was " << lowest << "." << endl;

    //cout << "The area was " << r << "." << endl;
}
4

1 回答 1

2

声明一个结构体,其字段为doublestring

struct A
{ 
   double count;
   string region;
};

将每个区域名称及其对应的计数存储在其中。将findLowest如下所示:

void findLowest(A n, A s, A e, A w, A c) 
{

     double low=n.count;
     string reg=n.region;
     if(s.count<low)
     {
         low=s.count;
         reg=s.region;
      }

     if(e.count<low)
     {
         low=e.count;
         reg=e.region;
      }
      if(w.count<low)
     {
         low=w.count;
         reg=w.region;
      }
     if(c.count<low)
     {
         low=c.count;
         reg=c.region;
      }
cout << "\nThe least number of accidents was " << low << "." << endl;

cout << "The area was " << reg << "." << endl;
}

另一种方法是使用C++ pair<string, double>. 的内部实现pair又是一个struct. 您可以使用 访问第一个元素first,使用 访问第二个元素second

pair< string, double > P;
P=make_pair("north", 12.12);
cout<<P.first<<" "<<P.second<<endl; //prints north 12.12..

另一种方法是使用C++ STL set. 创建一个set< pair <double, string > >. 为此,您无需明确找到最低值。set自动对插入其中的元素进行排序。示例代码如下所示:

set< double, string > St;
St.insert(make_pair(12.34, "north"));
St.insert(make_pair(34.56, "south"));
St.insert(make_pair(10.12, "east"));
cout<<St.begin()->second<<endl; //prints 'east'..

我不确定你是否熟悉set。但这里有一个参考。

于 2013-06-19T16:03:45.350 回答