正弦曲线编程代码怎么写

时间:2025-03-04 03:55:19 明星趣事

绘制正弦曲线的编程代码可以根据不同的编程语言和绘图库有所不同。以下是几种不同编程语言绘制正弦曲线的示例代码:

C语言

```c

include

include

int main() {

double x, y;

for (y = 1; y >= -1; y -= 0.1) {

x = asinh(y) * 10;

for (int i = 0; i <= 62; i++) {

if (i == (int)x || i == 62 - (int)x)

printf("*");

else

printf(" ");

}

printf("\n");

}

return 0;

}

```

C++

```cpp

include

include

include

int main() {

std::vector y_values = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0};

for (double y : y_values) {

int x = static_cast(y * 10);

for (int i = 0; i <= 62; i++) {

if (i == x || i == 62 - x)

std::cout << "*";

else

std::cout << " ";

}

std::cout << std::endl;

}

return 0;

}

```

Python

```python

import matplotlib.pyplot as plt

import numpy as np

x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)

y = np.sin(x)

plt.plot(x, y)

plt.show()

```

JavaScript

```javascript

function drawSinusoid(dot, amplitude, initialPhase, angularFrequency, setover, length, opts) {

var color = opts && opts.color ? opts.color : "DarkRed";

var max = length * 2 * Math.PI / angularFrequency;

var x = -2 * Math.PI / angularFrequency / 3;

var pre = [dot + x, dot + amplitude * Math.sin(angularFrequency * x + initialPhase) + setover];

var cur = [dot + x, dot + amplitude * Math.sin(angularFrequency * x + initialPhase) + setover];

for (; x < max; x += 5) {

var line = [pre + x, pre + amplitude * Math.sin(angularFrequency * x + initialPhase) + setover];

drawLine(pre, line, {color: color});

pre = cur;

cur = line;

}

}

```

这些代码示例展示了如何使用不同的编程语言和库来绘制正弦曲线。你可以根据自己的需求和编程环境选择合适的代码进行参考和修改。