c++ - 如何只显示有 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> 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
}
}
}
推荐阅读
- regex - htaccess 在 url 中用另一个参数替换一个参数
- javascript - 使用 Chrome materialize v1.0.0 时,鼠标滚轮滚动在 Materialise 下拉菜单中并不总是有效
- algorithm - 对排序后的数组中每个相邻元素之间存在 3 个差异的数组进行排序
- sql - 在 presto SQL 中将 int 格式化为日期
- reactjs - 在 stack-Navigator 屏幕内打开 React-Native 抽屉菜单
- ios - 如何以编程方式快速修复搜索栏
- java - 生成指定自定义原型描述符的 Maven 原型
- java - 如何在分页中显示有限的页面链接?
- c - 这个多个 void 指针函数是如何工作的?
- c - 在 cFS 中使用 OS_creat