如何只显示有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;
}

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

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> Cstd::vector会随着push_back中越来越多的元素而增长,并且它会跟踪包含的元素的数量,因此不需要传递向量的大小。C.size()会告诉你元素的数量
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vectorn";
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
}
}
}

最新更新