雉兔同笼用编程怎么写

时间:2025-01-28 13:36:41 网络游戏

Python

```python

def solve_雉兔同笼(heads, legs):

for chicken in range(heads + 1):

rabbit = heads - chicken

if 2 * chicken + 4 * rabbit == legs:

print(f'雉兔同笼,兔有 {rabbit} 只,雉有 {chicken} 只')

return

print('无解')

示例输入

solve_雉兔同笼(35, 94)

```

C++

```cpp

include

using namespace std;

int main() {

int heads, feet, chicken, rabbit;

cout << "请输入头的总数和脚的总数:" << endl;

cin >> heads >> feet;

rabbit = (feet - 2 * heads) / 2;

chicken = heads - rabbit;

if (rabbit >= 0 && chicken >= 0 && feet == 4 * chicken + 2 * rabbit) {

cout << "鸡的数量为:" << chicken << ",兔的数量为:" << rabbit << endl;

} else {

cout << "无解" << endl;

}

return 0;

}

```

Java

```java

public class ChickenRabbitInCage {

public static void main(String[] args) {

int heads = 35; // 头的总数

int legs = 94; // 脚的总数

int chicken, rabbit;

rabbit = (legs - 2 * heads) / 2;

chicken = heads - rabbit;

System.out.println("鸡的数量:" + chicken);

System.out.println("兔的数量:" + rabbit);

}

}

```

C

```csharp

using System;

class Program {

static void Main() {

int heads = 35; // 头的总数

int legs = 94; // 脚的总数

int chicken, rabbit;

rabbit = (legs - 2 * heads) / 2;

chicken = heads - rabbit;

Console.WriteLine("鸡的数量:" + chicken);

Console.WriteLine("兔的数量:" + rabbit);

}

}

```

JavaScript

```javascript

function solve_雉兔同笼(heads, legs) {

for (let chicken = 0; chicken <= heads; chicken++) {

let rabbit = heads - chicken;

if (2 * chicken + 4 * rabbit === legs) {

console.log(`雉兔同笼,兔有 ${rabbit} 只,雉有 ${chicken} 只`);

return;

}

}

console.log('无解');

}

// 示例输入

solve_雉兔同笼(35, 94);

```

这些代码示例展示了如何使用不同编程语言来解决雉兔同笼问题。你可以选择适合你的编程语言,并根据需要进行调整。