2016-11-27 110 views
0

我正在用C++編寫一些代碼來在一個圖形上顯示兩個圖形。一個功能需要是sin功能,另一個功能需要是cos功能。用C++創建正弦/餘弦圖形

我有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]; 
    } 
} 
+0

你有圖表庫嗎?它看起來像你試圖輸出到控制檯。 –

+1

如果你只是想快速繪製一些東西,你可能想看看gnuplot http://gnuplot.sourceforge.net/demo_5.0/simple.html或matplotlib http://matplotlib.org/examples/animation/ basic_example.html – moof2k

+0

我試圖格式化代碼,但是如果縮進不正確,您應該檢查我的編輯。儘管並非總是必要,但圍繞代碼塊使用括號「{..}」可以提高可讀性並使將來的編輯更容易。 – Tony

回答

0

您不會在圖表的每一行後面打印換行符。更換

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

​​

然後,它爲我工作。

但是,這似乎是一個有點令人費解的做法。如果是我,我會根據函數值計算x-es的座標,而不是掃描並檢查每個座標是否接近函數值。例如:

#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'; 
    } 
}