请4楼朋友看下面的程序吧。虽然是针对12个蛋的,但按您的意思,坏蛋已躲藏在9、10、11之中了。因此跟12个蛋的问题是一致的。
//寻找12个蛋中唯一不合格的蛋(输出详细的称量过程)
#include<iostream.h>
#include<math.h>
char w[]="第?次称量: ";
struct Egg{ int n; int w; };
// 蛋的编号 蛋重(克)
int wight3(Egg& a,Egg& b,Egg& c,int d)
{ int d3; w[2]='3'; cout<<w;
if((d3=a.w-b.w)==0)
{ cout<<a.n<<" = "<<b.n<<endl;return d<0?c.n:-c.n; }
else if(d3>0)
{ cout<<a.n<<" > "<<b.n<<endl;if(d>0)return a.n;else return -b.n; }
else if(d3<0)
{ cout<<a.n<<" < "<<b.n<<endl;if(d>0)return b.n;else return -a.n; }
}
int wight8(Egg *H,Egg *L)
{ int d2,d3; char s[]="?,?,? = ?,?,?\n";
s[0]=H[0].n+'0'; s[2]=H[1].n+'0'; s[4]=L[0].n+'0';
s[8]=H[2].n+'0';s[10]=H[3].n+'0';s[12]=L[1].n+'0';
w[2]='2'; cout<<w;
d2=(H[0].w+H[1].w+L[0].w)-(H[2].w+H[3].w+L[1].w);
if(d2==0){s[6]='=';cout<<s;d3=L[2].w-L[3].w;w[2]='3';
cout<<w<<L[2].n<<(d3>0?" > ":" < ")<<L[3].n<<endl;
return -L[2+(d3>0)].n;}
else if(d2>0){ s[6]='>';cout<<s;return wight3(H[0],H[1],L[1],+1); }
else if(d2<0){ s[6]='<';cout<<s;return wight3(H[2],H[3],L[0],+1); }
}
int weight12(Egg egg[])
{ char s1[]="1,2,3,4 = 5,6,7,8\n";
char s2[]="9,10 = 11,1\n"; int d1,d2,d3;
d1=(egg[1].w+egg[2].w+egg[3].w+egg[4].w)
-(egg[5].w+egg[6].w+egg[7].w+egg[8].w);
w[2]='1'; cout<<w;
if(d1==0)
{ s1[8]='='; cout<<s1; w[2]='2'; cout<<w;
d2=(egg[9].w+egg[10].w)-(egg[11].w+egg[1].w);
if(d2==0){s2[5]='='; cout<<s2;
d3=egg[12].w-egg[1].w;w[2]='3';cout<<w<<12
<<(d3>0?" > ":" < ")<<1<<endl;return d3*12;}
else {s2[5]=d2>0?'>':'<'; cout<<s2;
return wight3(egg[9],egg[10],egg[11],d2);}
}
else if(d1>0)
{ s1[8]='>';cout<<s1;return wight8(&egg[1],&egg[5]); }
else if(d1<0)
{ s1[8]='<';cout<<s1;return wight8(&egg[5],&egg[1]); }
}
void main()
{ int st,i; char *p;
Egg egg[12+1]; cout<<"不合格蛋号(?~?2): ";
while(1){cin>>st;if(st!=0&&abs(st)<=12)break;
cout<<"没有该号,请重新输入: ";}
for(i=1;i<=12;i++){egg[i].n=i;egg[i].w=60;}
if(st>0)egg[st].w++;else egg[-st].w--;
st=weight12(egg);p=st>0?" 偏重":" 偏轻";
cout<<"结论: NO."<< abs(st) << p <<endl;
}