这个程序应该根据购买的碗数从最高到最低打印出最受欢迎的拉面口味。
然而,如果我随机输入碗的销售量作为以下
(售出1个-用于阵列中的第一种口味(
(售出2个-用于阵列中的第二种口味(
(3个已售出-用于阵列中的第三种口味(
(4种为阵列中的第四种口味出售(
输出
鸡肉4
__3
__2
__1
但是,如果我按降序分配销售金额,该程序将工作
我真的很感谢你的反馈
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string flavor[]={"fish","lamp","steak" ,"chicken"} ;
int scoops[100]={};
int sum=0;
int x=0;
for(x=0;x<4;x++)
{
cout <<"enter amount of bowls for the following ramen flavor :"<<flavor[x] <<endl;
cin>>scoops[x];
sum=scoops[x]+sum;
}
cout <<"total number of bowls is "<<sum<<endl;
cout <<"list of the most popular flavors to least popular flavors "<<endl;//bubble sort
int i=0,j=0,temp,char tempf;
if(scoops[j]<scoops[j+1])
{
temp=scoops[j];
scoops[j]=scoops[j+1];
flavor[j]=flavor[j+1];
scoops[j+1]=temp;
flavor[j+1]=tempf;
}
for (int a=0;a<4;a++)
{
cout <<flavor[a] <<"t"<<scoops[a]<<endl;
}
}
您可以在您的场景中实现类似的气泡排序
int i = 0;
bool is_sorted = true;
int number_of_scoop_records = 4;
// We keep looping over the array until all the elements are sorted
while(true) {
if(i >= (number_of_scoop_records-1)) {
// All elements sorted, nothing to do anymore
if(is_sorted)
break;
// Lets go around again
i = 0;
is_sorted = true;
continue;
}
// Unsorted elements found
if(scoops[i+1] < scoops[i]) {
is_sorted = false;
std::swap(scoops[i+1], scoops[i]);
}
i++;
}
我认为你应该围绕spools[]数组进行迭代,检查它的值,并使用STL::算法为我们提供的swap((函数。
int length = sizeof(flavor)/sizeof(flavor[0]);
for (int i = 0; i < length-1; ++i)
{
for (int j = i+1; j < length; ++j)
{
if (scoops[i] > scoops[j])
{
swap(flavor[i], flavor[j]);
}
}
}