运行代码:
//函数图形化显示练习(进阶)
#include"std_lib_facilities.h"
#include"GUI/Simple_window.h"
#include"GUI/GUI.h"
#include"GUI/Graph.h"
#include"GUI/Point.h"
//定义函数
double one(double) { return 1; }
double slope(double x) { return x / 2; }
double square(double x) { return x * x; }
double sloping_cos(double x) { return slope(x) + cos(x); }
//-----------------------------------------------------------------------------
int main()
try
{
//定义常量
int xmax = 600;
int ymax = 600;//窗口尺寸
int xlength = 400;
int ylength = 400;//坐标轴长度
int x_scale = 20;
int y_scale = 20;//坐标轴缩放比例
Point orig(300, 300);//坐标轴原点
int r_min = -10;
int r_max = 11;//自变量范围
int n_points = 400;//显示的函数值数量
//--------------------------------------------------------------------------
//建立窗口
Simple_window win(Point(100, 100), xmax, ymax, "Function graphs");
//--------------------------------------------------------------------------
//建立坐标轴
Axis x(Axis::x, Point(100, 300), xlength,x_scale, "1==20 pixels");
x.set_color(Color::red);
Axis y(Axis::y, Point(300, 500), ylength, y_scale, "1==20 pixels");
y.set_color(Color::red);
win.attach(x);
win.attach(y);
//---------------------------------------------------------------------------
//构造函数
Function f1(one, r_min, r_max, orig, n_points, 1, 1);
f1.set_color(Color::black);
win.attach(f1);
Function f2(slope, r_min, r_max, orig, n_points, x_scale, y_scale);
f2.set_color(Color::black);
win.attach(f2);
Function f3(square, r_min, r_max, orig, n_points, x_scale, y_scale);
f3.set_color(Color::black);
win.attach(f3);
Function f4(cos, r_min, r_max, orig, n_points, x_scale, y_scale);
f4.set_color(Color::blue);
win.attach(f4);
Function f5(sloping_cos, r_min, r_max, orig, n_points, x_scale, y_scale);
f5.set_color(Color::black);
win.attach(f5);
//----------------------------------------------------------------------------
//为函数添加标签
Text t1(Point(100, 420), "x/2");
t1.set_color(Color::black);
win.attach(t1);
//-----------------------------------------------------------------------------
//启动GUI
win.wait_for_button();
//----------------------------------------------------------------------------
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
运行结果: