C++找次品

今天我们在数学课上学习了用天平找次品。
(以下几张图片来自课本库网)
在这里插入图片描述
在这里插入图片描述
哈哈,根据道理我又能写程序了。

//Author:PanDaoxi
#include <iostream>
using namespace std;
int x,y,z; 
int find(int n){
    
    
	if(y==2){
    
    
		cout<<1<<" "<<1<<endl;
		return 0;
	}
	if(x==1&&y==1) return 0;
	z=n%3,x=n/3,y=n/3;
	if(z==2){
    
    
		x++;
		y++;
	}
	else if(z==1) y++;
	else x=y;
	cout<<x<<" "<<x<<" "<<y<<endl;
	find(y);
}
int main(){
    
    
	int n;
	cin>>n;
	if(n==1){
    
    
		cout<<-1<<endl;
		return 0;
	}
	find(n);
	return 0;
} 

这个程序可以输出具体的称重过程:
在这里插入图片描述
也可以根据范围,求出需要的次数,在这里不写了。
例如有100个零件,100在34~35之间,则需要5次即可。

猜你喜欢

转载自blog.csdn.net/PanDaoxi2020/article/details/121864695
今日推荐