要使用C語言的sin()
函數繪制波形圖,您需要使用一個庫來繪制圖形
#include<stdio.h>
#include <math.h>
#include <SDL2/SDL.h>
const int WIDTH = 800;
const int HEIGHT = 600;
const double PI = 3.14159265358979323846;
int main(int argc, char* argv[]) {
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_Surface* surface = NULL;
SDL_Texture* texture = NULL;
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Error: %s\n", SDL_GetError());
return -1;
}
// Create window and renderer
window = SDL_CreateWindow("Sine Wave", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("Error: %s\n", SDL_GetError());
return -1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
printf("Error: %s\n", SDL_GetError());
return -1;
}
// Set render draw color
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
// Clear screen
SDL_RenderClear(renderer);
// Set render draw color for sine wave
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
// Draw sine wave
for (int x = 0; x < WIDTH; x++) {
double angle = (double)x / WIDTH * 2 * PI;
int y = HEIGHT / 2 + sin(angle) * HEIGHT / 4;
SDL_RenderDrawPoint(renderer, x, y);
}
// Update screen
SDL_RenderPresent(renderer);
// Wait for key press to exit
SDL_Event event;
while (SDL_WaitEvent(&event)) {
if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
break;
}
}
// Cleanup
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
這個示例程序使用了SDL2庫來創建一個窗口并在其中繪制一個正弦波形。首先,我們初始化SDL并創建一個窗口和渲染器。然后,我們設置渲染器的繪制顏色并清除屏幕。接下來,我們遍歷屏幕上的每個像素點,計算對應的正弦值,并將其繪制到屏幕上。最后,我們更新屏幕并等待用戶按下鍵盤上的ESC鍵或單擊窗口關閉按鈕以退出程序。
要編譯此程序,請確保已安裝SDL2庫,并使用以下命令進行編譯:
gcc sinewave.c -o sinewave -lSDL2
運行生成的可執行文件(例如./sinewave
),您將看到一個包含正弦波形的窗口。