Title: Total number of chickens and rabbits: N, total number of legs: M. input n,m, output the number of chickens and rabbits respectively; no solution output "no answer"
Sample Output 1:
14 32
Sample Output 1:
12 2
Sample Input 2:
10 16
Sample Output 2:
No Answer
First, declare two variables n,m corresponding total and total leg number, and then declare two variables for the number of chickens and rabbits each, a, b
1 int n,m,a,b;
Input n,m:
scanf ("%d%d", &n,&m);
Through simultaneous equations:
A+b=n
2a+4b=m
Have
A= (4n-m)/2; b=n-a;
Determine if there is no solution:
1. The total leg number m cannot be odd
2.a>=0
3.b>=0
The
if (m%2= =1| | a<0| | b<0) printf ("No answer");
If there is a solution, the output is a, B:
Else printf ("%d%d", A, b);
Full code:
//P9 case 1-4 chicken and rabbit cage#include <cstdio>intN,m;//N: Total m: Total number of legsintMain () {intb;//A: The number of chickens B: the number of rabbitsscanf ("%d%d", &n,&m);//total number of inputs N and total number of legs Ma=(4*N-M)/2;//simultaneous equations 2a+4b=m and A+b=nb=n-A; if(m%2==1|| a<0|| b<0)//The total number of legs cannot be odd and the number of chickens and rabbits cannot be negative.printf"No Answer"); Elseprintf ("%d%d", A, b); return 0; }
An introduction to the C + + algorithm race Classic Page9 example 1-4 chicken and rabbit cage