有10箱产品每箱有1000件,正品每件100克。其中的几箱是次品,次品每件比正品轻10克,问能否用秤只称一次,就找出哪几箱是次品。
#include <iostream>
//#include <string>
using namespace std;
int main()
{
int n;
//输入箱子数量
cout<<"input the number of boxes:";
cin>>n;
//标准总重量
long w1 = 0;
long w2 = 0;
int t = 1;
for (int i = 0;i<n;++i)
{
//w1是取出的总件数
w1 += t;
cout<<i+1<<" boxes take "<<t<<" units."<<endl;
//根据规律推算得出,拿的件数呈现2的指数次增长
t *= 2;
}
//此时w1是取出的理想总重量
w1 = w1 *100;
cout<<"normal weight:"<<w1<<endl;
cout<<"Input reality weight:";
//W2是实际取出的总质量
cin>>w2;
//w1是质量差
w1 -= w2;
//w1是次品件数
w1 /= 10;
while (w1>0)
{
int k = 0;
int t=1;
//计算最接近当前件数w1的2^k,则k+1号箱为次品箱
while(w1-t>=0)
{
t *= 2;
++k;
}
w1 -= t/2;
cout<<k<<" box is bad."<<endl;
}
return 0;
}