在C语言中绘制折线图通常需要使用图形库,例如OpenGL或者SDL。下面是一个使用SDL库绘制简单折线图的示例代码:
#include#define WIDTH 800 #define HEIGHT 600 void drawLine(SDL_Renderer *renderer, int x1, int y1, int x2, int y2) { SDL_RenderDrawLine(renderer, x1, HEIGHT - y1, x2, HEIGHT - y2); // SDL坐标原点在左上角,y轴朝下,需要转换坐标 } int main() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { SDL_Log("Unable to initialize SDL: %s", SDL_GetError()); return 1; } SDL_Window *window = SDL_CreateWindow("Line Chart", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0); if (window == NULL) { SDL_Log("Unable to create window: %s", SDL_GetError()); return 1; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { SDL_Log("Unable to create renderer: %s", SDL_GetError()); return 1; } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // 设置画布颜色为白色 SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // 设置画笔颜色为黑色 drawLine(renderer, 100, 100, 200, 200); // 绘制折线 SDL_RenderPresent(renderer); SDL_Delay(3000); // 延迟3秒 SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }
这段代码使用SDL库绘制了一个简单的折线图,包括设置窗口大小,创建窗口和渲染器,绘制折线,以及销毁窗口和渲染器等操作。你可以根据自己的需求修改绘制的折线图的坐标和样式。