Aufgabe 8
Schwierigkeitsgrad: Einfach
Themen: Kontrollstrukturen Funktionen BitmapPlusPlus
- Aufgabenstellung
- Lösung
Schreiben Sie ein Programm, das mithilfe der Funktionen aus BitmapPlusPlus.hpp eine Funktion grafisch darstellt. Erstellen Sie dazu zunächst ein Bild mit einer Auflösung von 200×200 Pixeln, initialisieren Sie es mit weißen Pixeln und speichern Sie es anschließend.
Implementieren Sie folgende Funktionen:
- Eine Funktion, die die Achsen des Graphen sowie die Skalierung (Markierungen alle 10 Pixel) zeichnet.
- Eine Funktion void draw_function(Bitmap &graph, float (*function)(float)), die das Bild und einen Zeiger auf die zu plottende Funktion entgegennimmt. Diese Funktion berechnet alle Punkte und zeichnet sie in das Bild ein. Um die übergebene Funktion auszuwerten, können Sie zum Beispiel y = function(value) verwenden.
info
Hinweise:
- Achten Sie darauf, nicht außerhalb des Bildes zu zeichnen.
- Nutzen Sie type casting (z.B.
int a = int(2.0);) umfloatinintund umgekehrt umzuwandeln.
Testen Sie ihr Programm mit den folgenden Funktionen:
float x_square(float x){
return 0.1* x * x;
}
float x_cube(float x){
return 0.01 * x * x * x;
}
float x_sine(float x){
return 50 * sin(x / 10);
}
float x_division(float x){
return 50 / (x + 1);
}
#include "BitmapPlusPlus.hpp"
#include <cmath>
using bmp::Bitmap, bmp::Pixel;
#define HEIGHT 200
#define WIDTH 200
void draw_axis(Bitmap &graph){
// Draw x-axis
for(int x = 0; x < WIDTH; x++) {
graph.set(x, HEIGHT / 2, bmp::Black);
}
// Draw y-axis
for(int y = 0; y < HEIGHT; y++) {
graph.set(WIDTH / 2, y, bmp::Black);
}
// Draw Horizontal scale lines
for(int i = 0; i < WIDTH; i += 10) {
graph.set(i, HEIGHT / 2 - 1, bmp::Black);
graph.set(i, HEIGHT / 2 + 1, bmp::Black);
}
// Draw Vertical scale lines
for(int i = 0; i < HEIGHT; i += 10) {
graph.set(WIDTH / 2 - 1, i, bmp::Black);
graph.set(WIDTH / 2 + 1, i, bmp::Black);
}
}
void draw_function(Bitmap &graph, float (*function)(float)) {
for(int x = 0; x < WIDTH; x++){
// Calculate the y values
float y = function(float(x - WIDTH / 2));
int plot_y = HEIGHT / 2 - int(y);
// Ensure the y value is within bounds
if(plot_y >= 0 && plot_y < HEIGHT) {
graph.set(x, plot_y, bmp::Blue);
}
}
}
float x_square(float x){
return 0.1* x * x;
}
float x_cube(float x){
return 0.01 * x * x * x;
}
float x_sine(float x){
return 50 * sin(x / 10);
}
float x_division(float x){
return 50 / (x + 1);
}
int main(){
Bitmap graph(HEIGHT, WIDTH);
graph.clear(bmp::White);
draw_axis(graph);
draw_function(graph, x_sine);
graph.save("graph.bmp");
}