一起创业网-为互联网创业者服务

左右对称程序怎么写

编写一个左右对称的程序,可以根据不同的编程语言和需求有不同的实现方法。以下是几种不同编程语言中实现左右对称的示例代码:

1. Python 示例

使用 Python 和 matplotlib 库绘制一个左右对称的心形曲线:

```python

import matplotlib.pyplot as plt

import numpy as np

def draw_symmetric_shape():

t = np.linspace(0, 2 * np.pi, 100)

x = 16 * np.sin(t)3

y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)

return x, y

x, y = draw_symmetric_shape()

plt.figure(figsize=(6, 6))

plt.plot(x, y, label='Heart Curve')

plt.axvline(x=0, color='red', linestyle='--')

plt.legend()

plt.show()

```

2. C++ 示例

使用 C++ 编写一个简单的程序来判断一个字符串是否左右对称:

```cpp

include

include

include

bool is_palindrome(const std::string& str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str[left] != str[right]) {

return false;

}

left++;

right--;

}

return true;

}

int main() {

std::string input;

std::cout << "请输入一个字符串: ";

std::getline(std::cin, input);

if (is_palindrome(input)) {

std::cout << "字符串是左右对称的" << std::endl;

} else {

std::cout << "字符串不是左右对称的" << std::endl;

}

return 0;

}

```

3. Java 示例

使用 Java 编写一个简单的程序来判断一个字符串是否左右对称:

```java

import java.util.Scanner;

public class PalindromeChecker {

public static boolean isPalindrome(String str) {

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

}

left++;

right--;

}

return true;

}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("请输入一个字符串:");

String input = scanner.nextLine();

if (isPalindrome(input)) {

System.out.println("字符串是左右对称的");

} else {

System.out.println("字符串不是左右对称的");

}

}

}

```

4. 数组对称示例

使用 C++ 编写一个程序来判断一个二维数组是否关于主对角线对称: