有10箱产品,每箱有1000件,其中正品每件100克。其中有几箱是次品,每件次品比正品轻10克,问能否用秤只称一次,就找出哪几箱是次品?

#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;
}
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值