在下面的代码中,我正在根据饮食计划找到我必须吃的晚餐。我通过饮食、午餐和早餐作为输入,而必须返回晚餐作为输出。饮食包含我今天应该吃的东西。每个字母都是一些食物。早餐和午餐包含我已经吃过的东西。
如果早餐或午餐包含饮食中不存在的任何元素,我应该返回“Cheater”。否则,我必须找到饮食中存在但早餐和午餐中没有的元素。
我的代码显示晚餐已成功计算。但它不返回晚餐。
#include <iostream>
#include <string>
using namespace std;
class DietPlan
{
public:
string chooseDinner( string diet, string breakfast, string lunch )
{
int lim1 = breakfast.length(), lim2 = lunch.length();
int flag1 = 1, lim0 = diet.length();
//Sort diet.
for(int k = 1; k < lim0; k++)
for(int x=0;x < lim0-k; x++)
if( diet[x]>diet[x+1] )
{
char temp = diet[x];
diet[x] = diet[x+1];
diet[x+1]=temp;
}
cout<<"Diet: "<<diet<<endl;
//Sort breakfast.
if(lim1>0)
for(int k = 1; k < lim1; k++)
for(int x=0;x < lim1-k; x++)
if( breakfast[x]>breakfast[x+1] )
{
char temp1 = breakfast[x];
breakfast[x] = breakfast[x+1];
breakfast[x+1]=temp1;
}
cout<<"Breakfast: "<<breakfast<<endl;
//Sort lunch.
if(lim2>0)
for(int k = 1; k < lim2; k++)
for(int x=0;x < lim2-k; x++)
if( lunch[x]>lunch[x+1] )
{
char temp2 = lunch[x];
lunch[x] = lunch[x+1];
lunch[x+1]=temp2;
}
cout<<"Lunch: "<<lunch<<endl;
//compare breakfast and diet. as soon as there is a difference flag 0.
for( int l = 0; l < lim1; l++ )
{
for(int m = 0; m<lim0; m++ )
if( breakfast[l]!=diet[m] )
flag1 = 0;
else
{
flag1 = 1;
cout<<diet[m];
diet[m] = '0'; cout<<" ho "<<endl;
break;
}
if( flag1 == 0 )
{
cout<<"Hicheater"<<endl;
return "CHEATER";
}
}
cout<<"Diet: "<<diet<<endl;
//compare lunch and diet. as soon as there is a difference flag 0.
for( int l = 0; l < lim2; l++ )
{
for(int m = 0; m<lim0; m++ )
if( lunch[l]!=diet[m] )
flag1 = 0;
else
{
flag1 = 1;
diet[m] = '0';
break;
}
if( flag1 == 0 )
return "CHEATER";
}
cout<<"Diet: "<<diet<<endl;
string dinner;
int i = 0;
// put the remaining characters from diet in dinner.
for( int k = 0; k<lim0; k++ )
if( diet[k]!='0' ) {
cout<<diet[k];
dinner[i] = diet[k];
cout<<i<<" "<<dinner[i]<<endl;
i++;
}
cout<<i<<endl;
dinner[i]='\0';
cout<<"Dinner: "<<dinner<<endl;
return dinner;
}
};
int main()
{
string diet = "ABCD";
string bf = "AB", lu = "C";
DietPlan d;
string din = d.chooseDinner(diet, bf, lu);
cout<<"Dinner: "<<din<<endl;
}
输出:
Diet: ABCD
Breakfast: AB
Lunch: C
A ho
B ho
Diet: 00CD
Diet: 000D
D0 D
1
Dinner:
Dinner:
晚餐没有显示任何东西。我真诚地感谢任何帮助。