要使用C语言实现sin()函数的图形化展示,你需要使用一些库来绘制图形
sudo apt-get install libsdl2-dev
接下来,创建一个名为sin_graph.c
的文件,并将以下代码复制到其中:
#include <SDL.h>
#include <math.h>
#include <stdbool.h>
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define SCALE 100
int main(int argc, char *argv[]) {
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
SDL_Surface *surface = NULL;
SDL_Texture *texture = NULL;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return -1;
}
window = SDL_CreateWindow("Sin Graph", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return -1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
return -1;
}
surface = SDL_CreateRGBSurface(0, WINDOW_WIDTH, WINDOW_HEIGHT, 32, 0, 0, 0, 0);
if (surface == NULL) {
printf("Surface could not be created! SDL Error: %s\n", SDL_GetError());
return -1;
}
texture = SDL_CreateTextureFromSurface(renderer, surface);
if (texture == NULL) {
printf("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError());
return -1;
}
SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF));
for (int x = 0; x < WINDOW_WIDTH; x++) {
double angle = (double)x / WINDOW_WIDTH * 2 * M_PI;
int y = (int)(WINDOW_HEIGHT / 2 + sin(angle) * SCALE);
Uint32 color = SDL_MapRGB(surface->format, 0x00, 0x00, 0xFF);
SDL_Rect rect = {x, y, 1, 1};
SDL_FillRect(surface, &rect, color);
}
SDL_UpdateTexture(texture, NULL, surface->pixels, surface->pitch);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
SDL_Delay(5000);
SDL_DestroyTexture(texture);
SDL_FreeSurface(surface);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
保存文件后,打开终端并导航到包含sin_graph.c
的目录。然后运行以下命令以编译和运行程序:
gcc sin_graph.c -o sin_graph -lSDL2
./sin_graph
这将显示一个窗口,其中包含sin()函数的图形化表示。窗口将在5秒后自动关闭。你可以根据需要调整窗口大小、颜色和比例。