输入鸡兔的总只数和脚总数,求鸡和兔的个数
输入鸡兔的总只数和脚总数,求鸡和兔的个数
这是一本书上的练习题,我是初学者,怎么编好像都不对,请教各位!
[解决办法]
你试试这样,前几天好象有人问过的。
static void Main()
{
int chicks;
int rabbits;
chickandrabbit(10, 34, out chicks, out rabbits);
if (chicks >= 0 && rabbits >= 0)
Console.WriteLine("鸡:{0}\t 兔:{1}", chicks, rabbits);
else
Console.WriteLine("无解!");
}
public static void chickandrabbit(int numbers, int feet, out int chicks, out int rabbits)
{
int temp = 4 * numbers - feet;
if (temp % 2 == 0)
{
chicks = temp / 2;
rabbits = numbers - chicks;
}
else
{
chicks = -1;
rabbits = -1;
}
}
鸡:3 兔:7
int 总只数 = ...;
int 总脚数 = ...;
for (int x = 0; x <= 总只数; x++)
for (int y = 0; y <= 总只数 - x; y++)
if (x * 2 + y * 4 == 总脚数)
Console.WriteLine("鸡 {0}, 兔 {1}.", x, y);
Dim 总只数 As Integer = ...
Dim 总脚数 As Integer ...
Dim x As Integer, y As Integer
For x = 0 To 总只数
For y = 0 To 总只数 - x)
If x * 2 + y * 4 = 总脚数 Then
Console.WriteLine("鸡 {0}, 兔 {1}.", x, y)
End If
Next
Next
Dim feet As Integer = ... //eg 52
Dim num As Integer = ... //eg 18
Dim cnum As Integer = (4 * num - feet) >> 1
Dim rnum As Integer = num - cnum
Console.WriteLine("rabbit:{0}, chick:{1}", rnum, cnum)