首页 > 解决方案 > 如何只显示有 5 个座位​​的汽车?

问题描述

我怎样才能让程序只显示有 5 个座位​​的汽车,现在无论如何,它会显示我写关于它们的信息的所有汽车,例如,如果我在控制台中写有 3 辆汽车并提供关于它们的信息和说一个有 2 个座位,其他有 5 个,在我运行程序后它仍然显示所有 3 个。知道如何只显示有 5 个座位​​的汽车吗?我可以以某种方式使用 quicksort() 函数吗?

#include <iostream>

using namespace std;

struct Car
{
    int no_seats;
    int year;
    char brand[20];
    char color[20];
    float horse_power;
};

void read_cars(Car C[], int &n)
{
    int i;
    cout << "Number of parked cars "; cin >> n;
    for(i=1; i<=n; i++)
    {  
       cout << "Brand " ; cin >> M[i].brand;
       cout << "The year it was made in " ; cin >> M[i].year;
       cout << "Color " ; cin >> M[i].color;
       cout << "Power " ; cin >> M[i].horse_power;  
       cout << "Number of seats " ; cin >> M[i].no_seats;
    }  

}

void display_cars(Car C[], int n)
{
    int i;
    for(i=1; i<=n; i++)
    {
       cout << "Brand " ; cout << M[i].brand << endl;
       cout << "The year it was made in " ; cout << M[i].year << endl;
       cout << "Color " ; cout << M[i].color << endl;
       cout << "Power " ; cout << M[i].horse_power << endl; 
       cout << "Number of seats " ; cout << M[i].no_seats << endl;
    }

}

int main()
{
    Car C[50];
    int n;

    read_cars(M, n);
    display_cars(M, n);

    return 0;
}

标签: c++sorting

解决方案


您需要在循环中添加一个条件:

void display_cars(Car C[], int n)
{
    int i;
    for(i=1; i<=n; i++)
    {
       if(M[i].no_seats == 5)        //     <-   like this
       {
          cout << "Brand " ; cout << M[i].brand << endl;
          cout << "The year it was made in " ; cout << M[i].year << endl;
          cout << "Color " ; cout << M[i].color << endl;
          cout << "Power " ; cout << M[i].horse_power << endl; 
          cout << "Number of seats " ; cout << M[i].no_seats << endl;
       }
    }
}

其他注意事项:

  • n只能上去49——记住这一点。这也意味着您正在浪费一个元素M[0](是的,数组在 C++ 中为零)。
  • 更喜欢使用std::vector<Car> C固定大小的数组。Astd::vector随着push_back越来越多的元素进入它而增长 - 它会跟踪包含元素的数量,因此您不需要传递向量的大小。C.size()会告诉你元素的数量。
void display_cars(const std::vector<Car>& C)
{
    std::cout << "There are " << C.size() << " cars in the vector\n";

    for(const Car& a_car : C)    // a range based for-loop
    {
        if(a_car.no_seats == 5)  // a_car will be a reference to each car in the loop
        {
            // use "a_car" to display info about one particular car
        }
    }
}

推荐阅读