C++ 我怎样才能只展示5个座位的汽车?
我怎样才能让程序只显示有5个座位的汽车,现在不管怎样,它都会显示我写的关于它们的信息的所有汽车,例如,如果我在控制台中写下有3辆汽车,并给出关于它们的信息,然后说一辆有2个座位,而另一辆有5个座位,在我运行程序后,它仍然会显示所有3辆汽车。你知道我怎么才能只展示5个座位的汽车吗?我可以使用quicksort()函数吗C++ 我怎样才能只展示5个座位的汽车?,c++,sorting,C++,Sorting,我怎样才能让程序只显示有5个座位的汽车,现在不管怎样,它都会显示我写的关于它们的信息的所有汽车,例如,如果我在控制台中写下有3辆汽车,并给出关于它们的信息,然后说一辆有2个座位,而另一辆有5个座位,在我运行程序后,它仍然会显示所有3辆汽车。你知道我怎么才能只展示5个座位的汽车吗?我可以使用quicksort()函数吗 #include <iostream> using namespace std; struct Car { int no_seats; int ye
#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;
}
#包括
使用名称空间std;
结构车
{
int no_座位;
国际年;
char品牌[20];
炭色[20];
浮动马力;
};
无效读取车辆(车辆C[],内部和外部)
{
int i;
cout>n;
对于(i=1;i M[i]),品牌;
cout>M[i].年;
cout>M[i]。颜色;
cout>M[i].马力;
cout>M[i],没有座位;
}
}
无效显示车辆(车辆C[],内部n)
{
int i;
对于(i=1;i,您需要在循环中添加一个条件:
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;
}
}
}
与您的问题无关,但您的循环中有一个“一个一”的错误。C++中的数组索引从零开始,即<代码> a(0)< /C> >数组的第一个元素<代码> < <代码>。循环从<代码> 1代码>到<代码> n>代码>(如果<代码> n<代码>是数组中的元素数)将超过数组末尾一个,并导致未定义的行为。在代码中为n
输入50
值即可。谢谢,我不认为if语句是我所需要的全部,我的意思是我尝试过了,但我认为我主要是这样做的,而且不起作用。再次感谢您的帮助:))
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
}
}
}