#include <iostream>
#include <vector>
//#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 += t;
cout<<i+1<<" boxes take "<<t<<" units."<<endl;
t *= 2;
}
w1 = w1 *100;
cout<<"normal weight:"<<w1<<endl;
cout<<"Input reality weight:";
cin>>w2;
w1 -= w2;
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;
}
运行结果:
解法二:通过C语言的库函数来求最接近当前重量w1的
#include <iostream>
#include <cmath>
#include <vector>
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 += t;
cout<<i+1<<" boxes take "<<t<<" units."<<endl;
t *= 2;
}
w1 = w1 *100;
cout<<"normal weight:"<<w1<<endl;
cout<<"Input reality weight:";
cin>>w2;
w1 -= w2;
w1 /= 10;
while (w1>0)
{
int k = 0;
int t=1;
//计算最接近当前重量w1的2^k,则k+1号箱为次品箱
k = log((double)w1)/log((double)2);
cout<<k+1<<" box is bad."<<endl;
w1 -= pow((double)2,k);
}
return 0;
}