枚举 PROBLEM2 银币称量问题

本文介绍了一个使用C++编写的程序,该程序通过三次称重来确定12枚硬币中哪一枚是伪币,并判断其是否比真币更重或更轻。文章详细展示了如何使用数组存储输入信息,以及如何编写函数来判断每枚硬币是否为伪币及其重量属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*some coins weigh 3 times can  identify which one is conterfeitcounterfeit. */
#include <cstdlib>
#include <iostream>


using namespace std;
/**store the input*/
char left1[3][7];   //用数组的时候记得给数组确定范围 
char right1[3][7];
char result1[3][6]; 
bool isheavy(char);   
bool islight(char);

int main()
{
    int n=0;
    scanf("%d",&n);
    while(n>0)
    {
        for(int i=0;i<3;i++)
        {
               cin>>left1[i]>>right1[i]>>result1[i];
        }
        /**numerate all coins and judge if it is light or heavy*/
        for(char c='a';c<='l';c++)   
        {
                 if(isheavy(c))
                 {
                               printf("%c is the counterfeit and it is heavy",c);
                               break;
                 }
                 if(islight(c))
                 {
                               printf("%c is the counterfeit and it is light",c);
                               break;
                 }
        }
        n--;   
    }   
    system("PAUSE");
    return EXIT_SUCCESS;
}
/**judge if the coin x satisfy the three weighings*/
bool isheavy(char x)
{
     for(int i=0;i<3;i++)
     {
             switch(result1[i][0])
             {
                  //if the coin x not exists in the down side, coin x is not the heavy, couterfeit one 
                  case 'd': if(strchr(right1[i],x)==NULL)  return false;
                  break;
                  case 'u': if(strchr(left1[i],x)==NULL)  return false;
                  break;
                  case 'e': if(strchr(left1[i],x)!=NULL||strchr(right1[i],x)!=NULL)  return false;
                  break;
             }
     }
     return true;
}

bool islight(char x)
{
     for(int i=0;i<3;i++)
     {
             switch(result1[i][0])
             {
                  case 'd' : if(strchr(left1[i],x)==NULL)  return false;
                  break;
                  case 'u' : if(strchr(right1[i],x)==NULL) return false;
                  break;
                  case 'e' : if(strchr(left1[i],x)!=NULL||strchr(right1[i],x)!=NULL) return false;
                  break;
             }
     }
     return true;
}
 
这次在字符串输入上花了很多时间。以后要注意c中对数组要给定其大小。
string a[0]形式的字符串数组需要用cin>>输入
char* a;  cin>>a  是错误的形式,因为a是一个指针。 
char* a; 用来定义动态数组   
a=new char[5];  cin>>a;

转载于:https://www.cnblogs.com/ggppwx/archive/2010/04/17/1714391.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值