用C 创建SIN/COS图



我在C 中编写一些代码,以在一个图上显示两个图。一个功能需要是sin函数,另一个功能需要是cos函数。

我有sin图和cos图所需的代码,但我无法将它们显示在一起。

#include <cmath>
#include <iostream>
#include <cstdlib>
using namespace std;
const float PI = 3.1459265;
int main()
{
    int size = 80, height = 21;
    char chart[height][size];
    size = 80, height = 21;
    double cosx[size];
    double sinx[size];
    {
        for (int i=0; i<size; i++)
            cosx[i] = 10*cos(i/4.5);
        for (int i=0; i<height; i++)
            for (int j=0; j<size; j++)
                if (-.01 < 10 - i - round(cosx[j]) && 10 - i - round(cosx[j]) <0.01)
                    chart[i][j] = 'x';
                else if (i==height/2)
                    chart[i][j] = '-';
                else
                    chart[i][j] = ' ';
        for (int i=0; i<height; i++)
            for (int j=0; j<size; j++)
                cout << chart[i][j];
        for (int i=0; i<size; i++)
            sinx[i] = 10*sin(i/4.5);
        for (int i=0; i<height; i++)
            for (int j=0; j<size; j++)
        if (-.01 < 10 - i - round(sinx[j]) && 10 - i - round(sinx[j]) <0.01)
            chart[i][j] = 'x';
        else if (i==height/2)
            chart[i][j] = '-';
        else
            chart[i][j] = ' ';
        for (int i=0; i<height; i++)
            for (int j=0; j<size; j++)
                cout << chart[i][j];
    }
}

您在图表的每一行之后不打印新线。更换

for (int i=0; i<height; i++)
    for (int j=0; j<size; j++)
       cout << chart[i][j];

for (int i=0; i<height; i++) {
    for (int j=0; j<size; j++) {
       cout << chart[i][j];
    }
    cout << 'n';
}

然后它对我有用。

但是,这似乎是一种令人费解的方法。如果是我,我将从函数值中计算X-E的坐标,而不是扫描并检查每个坐标是否接近函数值。示例:

#include <cmath>
#include <iostream>
#include <string>
#include <vector>
int main()
{
  int size = 80, height = 21;
  // Start with an empty chart (lots of spaces and a line in the middle)
  std::vector<std::string> chart(height, std::string(size, ' '));
  chart[height/2] = std::string(size, '-');
  // Then just put x-es where the function should be plotted
  for(int i = 0; i < size; ++i) {
    chart[static_cast<int>(std::round(10 * std::cos(i / 4.5) + 10))][i] = 'x';
  }
  // and print the whole shebang
  for(auto &&s : chart) {
    std::cout << s << 'n';
  }
}

最新更新