请教个问题。。(古典称球问题)
//称球问题:12个外形相同的圆球,其中一个是次品,不知其轻重,其他11个球重量相同;
//有一天平,没有砝码;
//请用最快的方法找出次球。
#include<iostream>
using namespace std;
int a[12];//12个球的重量
int weight(int i,int j){ //第i个到第j个的重量和
int w=0;
for(int k=i;k<=j;k++) w+=a[k];
return w;
}
void chengqiu(int a[]){
if(weight(0,3)==weight(4,7)){
if(weight(0,1)==weight(8,9)){
if(weight(0,0)==weight(10,10))
cout<<"11";
else cout<<"10";
}
else if(weight(0,0)==weight(8,8))
cout<<"9";
else cout<<"8";
}
else if(weight(0,3)==weight(8,11)){
if(weight(4,5)==weight(8,9)){
if(weight(6,6)==weight(8,8))
cout<<"7";
else cout<<"6";
}
else if(weight(4,4)==weight(8,8))
cout<<"5";
else cout<<"4";
}
else if(weight(0,1)==weight(8,9)){
if(weight(2,2)==weight(8,8))
cout<<"3";
else cout<<"2";
}
else if(weight(0,0)==weight(8,8))
cout<<"1";
else cout<<"0";
}
int main(){
int a[12]={1,1,1,1, 1,1,0,1, 1,1,1,1};
chengqiu(a);
system("pause");
}
-------------------------------
这个程序执行结果不对。但稍微改动了一下:
//称球问题:12个外形相同的圆球,其中一个是次品,不知其轻重,其他11个球重量相同;
//有一天平,没有砝码;
//请用最快的方法找出次球。
#include<iostream>
using namespace std;
int a[12]={1,1,1,2,1,1,1,1,1,1,1,1};;//12个球的重量
int weight(int i,int j){ //第i个到第j个的重量和
int w=0;
for(int k=i;k<=j;k++) w+=a[k];
return w;
}
void chengqiu(int a[]){
…………
…………
}
int main(){
chengqiu(a);
system("pause");
}
就行了。不知道为什么,感觉还是数组定义的问题,哪位大哥帮小弟一下。 dev编译器编译。