暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

算法分析与设计学习笔记2鸡兔同笼问题

一笑不琅然 2020-03-11
224

问题描述

声明一下,此系列所有文章的代码实现都是使用C/C++。

鸡兔同笼问题:一个笼子里关着若干鸡和兔子(鸡2只脚,兔子4只,无例外),已知笼子里脚的总数为a。则笼子里的动物最少有多少只,最多有多少只?

  • 输入:

  • 2

  • 3

  • 20

  • 输出应为:

  • 0

  • 0

  • 5 10

实现方法、数学逻辑计算法

此算法仅仅是通过数学逻辑来进行推理

  1. #include <stdio.h>

  2. int Max(int);

  3. int Min(int);

  4. int main()

  5. {

  6. int num, max, min;

  7. while(1)

  8. {

  9. printf("Please enter the number of feet(note that the number is even, input negative exit):");

  10. scanf("%d",&num);

  11. if(num <= 0)

  12. break;

  13. if(num < 4 || num%2 != 0)

  14. {

  15. printf("0\n");

  16. }

  17. else

  18. {

  19. if(!(num%2))

  20. {

  21. max = Max(num);

  22. min = Min(num);

  23. printf("At least:%d\nThere is a maximum:%d\n",min,max);

  24. }

  25. }

  26. }

  27. return 0;

  28. }

  29. /// 定义Min函数计算最小值

  30. int Min(int num)

  31. {

  32. int min;

  33. if(num%4 == 0)

  34. {

  35. min = num/4;

  36. }

  37. else

  38. min = num / 4 + 1;

  39. return min;

  40. }

  41. /// 定义Max函数计算最大值

  42. int Max(int num)

  43. {

  44. int max;

  45. max = num/2;

  46. return max;

  47. }

运行结果

联系我

博客园:https://www.cnblogs.com/AWSG-Shaodw/ CSDN:https://blog.csdn.net/AngleWithShotgun/ 简书:https://www.jianshu.com/u/df7323cbc116 微信公众号:

一笑不琅然一个专注于搞事情的大学IT男


文章转载自一笑不琅然,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论