要使用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
),您将看到一个包含正弦波形的窗口。