一道华为编程题

1、 农场计数问题(20分)

问题描述:

已知某农场中有一群鸡和兔子,总共有M个头和N只脚,计算总共有多少鸡和兔子


要求实现函数:
int GetFowlsNum(int iHeadNum, int iFootNum, int *iChickenNum, int *iRabbitNum)
【输入】iHeadNum: 总共头的数量         iFootNum: 总共脚的数量
【输出】iChickenNum: 鸡的数量          iRabbitNum: 兔子的数量
【返回】 0: 找到符合要求的鸡和兔子的数量         -1: 未找到符合要求的数量

示例
输入:iHeadNum =201, iFootNum=604
输出:iChickenNum=100, iRabbitNum=101
返回:0
 
输入:iHeadNum =201, iFootNum=123
输出:iChickenNum=0, iRabbitNum=0

返回:-1


程序实现:

/*
  Name: GetFowlsNum.cpp
  Copyright: Candy@2012
  Author: Candy
  Date: 29/02/12 10:51
  Description: int GetFowlsNum(int iHeadNum, int iFootNum, int *iChickenNum, int *iRabbitNum)
 【input】iHeadNum: the total number of heads, iFootNum: the total number of foot

 【output】iChickenNum: the total number of chicken, iRabbitNum: the total number of rabbit
 【return】 0: find the right number of chicken and rabbit,

           -1: can not find the right bunber of chicken and rabbit,

  example:

       input:iHeadNum =201, iFootNum=604, output:iChickenNum=100, iRabbitNum=101, return:0

       input:iHeadNum =201, iFootNum=123, output:iChickenNum=0, iRabbitNum=0, return:-1 

 */

#include
#include

#define HeadNum 201
#define FootNum 604

int GetFowlsNum(int iHeadNum, int iFootNum, int *iChickenNum, int *iRabbitNum)
{
    int k = 0;
    
    *iChickenNum =0;
    *iRabbitNum = 0;
    
    for (*iChickenNum = 0; *iChickenNum < (iHeadNum+1); (*iChickenNum)++)
    {
        *iRabbitNum =  iHeadNum - *iChickenNum;
        if ((2**iChickenNum + 4**iRabbitNum) == iFootNum)
        {
             printf("The number of chicken is %d, and the number of rabbit is %d\n\n", *iChickenNum, *iRabbitNum);
             k = 1;
        }
        
    }
    
    return k;
}

int main (void)
{
    int ChickenNum = 0, RabbitNum = 0;
    
    if (!GetFowlsNum(HeadNum, FootNum, &ChickenNum, &RabbitNum))
       printf("Can not find the right number of chicken and rabbit\n\n");
       
       system("pause");
       
    return 0;    
}

你可能感兴趣的:(编程)