Skip to content

Instantly share code, notes, and snippets.

@calebsander
Created October 9, 2019 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebsander/c5300e6eeca6f90dbc38e68637250db8 to your computer and use it in GitHub Desktop.
Save calebsander/c5300e6eeca6f90dbc38e68637250db8 to your computer and use it in GitHub Desktop.
CS 24 git Recitation — graphing program example
#include <math.h>
double y(double x) {
return sin(x);
}
#include <math.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
double y(double x);
void graph(double min_x, double max_x, double min_y, double max_y) {
struct winsize term_size;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &term_size);
int zero_col = round(min_x / (min_x - max_x) * term_size.ws_col - 0.5),
zero_row = round(max_y / (max_y - min_y) * term_size.ws_row - 0.5);
int col_rows[term_size.ws_col];
for (int col = 0; col < term_size.ws_col; col++) {
double x = min_x + (max_x - min_x) * (col + 0.5) / term_size.ws_col;
col_rows[col] =
round((max_y - y(x)) / (max_y - min_y) * term_size.ws_row - 0.5);
}
for (int row = 0; row < term_size.ws_row; row++) {
for (int col = 0; col < term_size.ws_col; col++) {
putchar(
col_rows[col] == row ? 'o' :
row == zero_row && col == zero_col ? '+' :
row == zero_row ? '-' :
col == zero_col ? '|' :
' '
);
}
putchar('\n');
}
}
#include <stdio.h>
#include <stdlib.h>
void graph(double min_x, double max_x, double min_y, double max_y);
int main(int argc, char **argv) {
if (argc != 5) {
fprintf(stderr, "Usage: %s min_x max_x min_y max_y\n", argv[0]);
return 1;
}
double min_x = atof(argv[1]), max_x = atof(argv[2]),
min_y = atof(argv[3]), max_y = atof(argv[4]);
if (!(min_x < max_x && min_y < max_y)) {
fputs("Invalid bounds\n", stderr);
return 1;
}
graph(min_x, max_x, min_y, max_y);
}
CC = clang-with-asan
CFLAGS = -Wall -Wextra
graph: function.o graph.o main.o
$(CC) $(CFLAGS) -lm $^ -o $@
%.o: %.c
$(CC) $(CFLAGS) -c $^ -o $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment