十二硬币判别代码
人间客制作
国外流行的 12 个硬币问题:12 硬币中可能有一个假的,而且不
知道假币比真币重还是轻,给你一架天平,天平没有示数,只能判断
是平衡还是不平,且只准称三次,让你判断是否有假币;如果有,找
出来。解法思想如下:
第一步:任选 8 个比较,如选:⑴⑵⑶⑷ 比 ⑸⑹⑺⑻
一、若一样重,则假币在⑼~⑿中,第二步:⑼⑽ 比⑾⑴
1.若一样重,则可能的假币为⑿。则第三步:⑴ vs ⑿
1)若一样重,则没有假币;
2)不一样重,则假币为⑿:如果(1)>(12),则假币轻,反之,
假币重;
2.若⑼⑽重,则第三步:⑼ 比 ⑽
1)若一样重,则假币为⑾(较轻)
2)不一样重,则假币为⑼、⑽中较重者
3.若⑼⑽轻,则第三步:⑼ 比 ⑽
1)若一样重,则假币为⑾(较重)
2)不一样重,则假币为⑼、⑽中较轻者
二、若⑴⑵⑶⑷重,则第二步:⑴⑵⑸ 比 ⑶⑷⑹
1.若一样重,则假币在⑺⑻中,第三步:⑺ 比 ⑻
假币为⑺、⑻中较轻者
2.若⑴⑵⑸端较重,则假币在⑴⑵⑹中,第三步:⑴比 ⑵
1)若一样重,则假币为⑹(较轻)
2)不一样重,则假币为⑴⑵中较重者
3.若⑶⑷⑹端较重,则假币在⑶⑷⑸中,第三步:⑶ 比 ⑷
1)若一样重,则假币为⑸(较轻)
2)不一样重,则假币为⑶、⑷中较重者
三、若⑴⑵⑶⑷轻,则与上面类似,第二步:⑴⑵⑸比 ⑶⑷⑹
1.若一样重,则假币在⑺⑻中,第三步:⑺ 比 ⑻
假币为⑺、⑻中较重者
2.若⑴⑵⑸端较轻,则假币在⑴⑵⑹中,第三步:⑴ 比 ⑵
1)若一样重,则假币为⑹(较重)
2)不一样重,则假币为⑴⑵中较轻者
3.若⑶⑷⑹端较轻,则假币在⑶⑷⑸中,第三步:⑶ 比 ⑷
1)若一样重,则假币为⑸(较重)
2)不一样重,则假币为⑶、⑷中较轻者
在科技发达的时代,我们都不愿意去做这样繁琐的比较,而是想
借助于计算机的威力,下面给大家介绍一种方法,可以在很短的时间
内完成中比较。当然,这类问题转化到编程上去后,主要考查的是大
家的编程思想,而不再是 12 硬币问题本身了,因为 12 个硬币的重量
需要大家自己去输入,这些数据只是为了检验大家程序的正确与否。
下面是该问题的代码:
#include
void main()
{
int i;
float a[12];
for(i=0;i<12;i++)
scanf("%f",&a[i]);
if(a[0]+a[1]+a[2]+a[3]==a[4]+a[5]+a[6]+a[7])
{
if(a[0]+a[1]+a[2]==a[8]+a[9]+a[10])
{
if(a[8]==a[11])
printf("There is no special coin!\n");
else if(a[8]>a[11])
printf("There is a special coin:%f(12) and it's lighter
than others.\n",a[11]);
else
printf("There is a special coin:%f(12) and it's heavier
than others.\n",a[11]);
}
else if(a[0]+a[1]+a[2]>a[8]+a[9]+a[10])
{
if(a[8]==a[9])
printf("There is a special coin:%f(11) and it's lighter
than others.\n",a[10]);
else if(a[8]>a[9])
printf("There is a special coin:%f(10) and it's lighter
than others.\n",a[9]);
else
printf("There is a special coin:%f(9) and it's lighter
than others.\n",a[8]);
}
else
{
if(a[8]==a[9])
printf("There is a special coin:%f(11) and it's heavier
than others.\n",a[10]);
else if(a[8]>a[9])
printf("There is a special coin:%f(9) and it's heavier
than others.\n",a[8]);
else
printf("There is a special coin:%f(10) and it's heavier
than others.\n",a[9]);
}
}
else if(a[0]+a[1]+a[2]+a[3]>a[4]+a[5]+a[6]+a[7])
{
if(a[0]+a[2]+a[5]==a[1]+a[4]+a[8])
{
if(a[6]==a[7])
printf("There is a special coin:%f(4) and it's heavier
than others.\n",a[3]);
else if(a[6]>a[7])
printf("There is a special coin:%f(8) and it's lighter
than others.\n",a[7]);
else
printf("There is a special coin:%f(7) and it's lighter
than others.\n",a[6]);
}
else if(a[0]+a[2]+a[5]>a[1]+a[4]+a[8])
{
if(a[0]==a[2])
printf("There is a special coin:%f(5) and it's lighter
than others.\n",a[4]);
else if(a[0]>a[2])
printf("There is a special coin:%f(1) and it's heavier
than others.\n",a[0]);
else
printf("There is a special coin:%f(3) and it's heavier
than others.\n",a[2]);
}
else
{
if(a[1]>a[8])
printf("There is a special coin:%f(2) and it's heavier
than others.\n",a[1]);
if(a[5]
a[7])
printf("There is a special coin:%f(7) and it's heavier
than others.\n",a[6]);
else