【发布时间】:2020-04-26 21:34:40
【问题描述】:
这个程序应该根据购买的碗的最高数量到最低打印出最受欢迎的拉面口味。
但是,如果我随机输入以下出售的碗数
(已售出 1 个 - 用于阵列中的第一个风味)
(已售出 2 个 - 阵列中的第二种口味)
(3 个已售出 - 阵列中的第三种口味)
(阵列中的第四种口味)
输出
鸡 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;
}
}
【问题讨论】:
-
冒泡排序需要一个循环。您的代码中没有循环,只有一个 if 语句。
-
使用
std::swap(scoops[j], scoops[j+1]); std::swap(flavor[j], flavor[j+1]);进行交换。您当前的交换是错误的,因为您在分配flavor[j]之前没有保存风味。 -
您的程序没有按原样编译(例如,您试图将
char tempf分配给std::string变量)。请提供minimal reproducible example
标签: c++ bubble-sort