【发布时间】:2017-07-01 02:39:28
【问题描述】:
有几行代码我想定义为一个函数,因为我打算多次使用它。部分代码如下:
// loop within loop used to reorder with highest price at the top
for(i=0;i<x;i++){
for(t=i;t<x;t++){
if(f[i].price < f[t].price) {
temp = f[i].price;
f[i].price = f[t].price;
f[t].price = temp;
}
}
}
我希望每次调用函数时都能为 x 和 f 输入新值。我在下面包含了我的所有代码。如果我无论如何都不清楚我的目标,请随时提问。我提前为不恰当的术语道歉,我对此并不陌生。谢谢
#include <iostream>
using namespace std;
struct List
{
char name[10];
int price;
};
int main()
{
//x represents number of structures within array!
int x;
cout << "How many items would you like to list under the fruit menu?\n";
cin >> x;
//array of structures fruit
struct List f[x];
int i;
//input values into structure
for (i = 0; i < x; i++) {
cout << "\nEnter fruit name, and price.\n";
cin >> f[i].name;
cin >> f[i].price;
};
//variables for reordering
int temp;
int t;
// loop within loop used to reorder with highest price at the top
for(i=0;i<x;i++){
for(t=i;t<x;t++){
if(f[i].price < f[t].price) {
temp = f[i].price;
f[i].price = f[t].price;
f[t].price = temp;
}
}
}
//Output of menus
//fruit Menu
cout << "\n\nFruit Menu";
for (i = 0; i < x; i++) {
cout << "\n" << f[i].name << " $" << f[i]. price;
};
return 0;
}
【问题讨论】:
-
那么你的问题是什么?
-
使用
std::sort()会好很多——冒泡排序几乎从来都不是一个好主意! -
提示:遵循一个相当古老的原则,即“将输入与输出分离”。所以编写一个收集输入的函数,编写一个重新排序的函数,然后编写一个打印结果的函数。然后以任何你喜欢的方式组合它们。
-
使用C++标准containers
标签: c++ arrays function struct