本帖最后由 人造人 于 2021-4-13 16:08 编辑
你不要再让我在数轴上写上数字,^_^
main.c#include "screen.h"
#include <math.h>
double radian(double angle) {
return angle * M_PI / 180;
}
void number_axis(screen_t *screen, size_t x, size_t y, char ch) {
for(size_t i = 1; i < screen->height - 1; ++i)
screen_putchar(screen, x, i, ch);
for(size_t i = 1; i < screen->width - 1; ++i)
screen_putchar(screen, i, y, ch);
}
void draw(screen_t *screen) {
ssize_t offset_x = 10;
ssize_t offset_y = screen->height / 2;
number_axis(screen, offset_x, offset_y, 'n');
for(size_t x = 1; x < screen->width - 1; ++x) {
screen_putchar(screen, offset_x + x, offset_y - 15 * sin(radian(8 * x)), '0');
}
}
int main(void) {
screen_t *screen = screen_init(130, 41);
screen_draw_border(screen, '#');
draw(screen);
screen_refresh(screen, stdout);
screen_deinit(screen);
return 0;
}
screen.h#ifndef _SCREEN_H_
#define _SCREEN_H_
#include <stdio.h>
#include <stddef.h>
typedef struct {
size_t width, height;
char *buff;
} screen_t;
screen_t *screen_init(size_t width, size_t height);
void screen_deinit(screen_t *screen);
void screen_putchar(screen_t *screen, size_t x, size_t y, char ch);
void screen_refresh(screen_t *screen, FILE *fp);
void screen_draw_border(screen_t *screen, char ch);
#endif
screen.c#include "screen.h"
#include <stdlib.h>
#include <string.h>
screen_t *screen_init(size_t width, size_t height) {
screen_t *screen = malloc(sizeof(*screen));
*screen = (screen_t){width, height, malloc(width * height)};
memset(screen->buff, ' ', screen->width * screen->height);
return screen;
}
void screen_deinit(screen_t *screen) {
free(screen->buff);
free(screen);
}
void screen_putchar(screen_t *screen, size_t x, size_t y, char ch) {
if(x < screen->width && y < screen->height)
screen->buff[y * screen->width + x] = ch;
}
void screen_refresh(screen_t *screen, FILE *fp) {
for(size_t y = 0; y < screen->height; ++y) {
for(size_t x = 0; x < screen->width; ++x) {
fputc(screen->buff[y * screen->width + x], fp);
}
fputc('\n', fp);
}
}
void screen_draw_border(screen_t *screen, char ch) {
for(size_t y = 0; y < screen->height; ++y) {
for(size_t x = 0; x < screen->width; ++x) {
if(y == 0 || x == 0 || y == screen->height - 1 || x == screen->width - 1)
screen_putchar(screen, x, y, ch);
}
}
}
|