2023-02-18 17:39:21 -05:00
|
|
|
//
|
2023-03-30 09:40:13 -04:00
|
|
|
// Often, C functions are used where no equivalent Zig function exists
|
|
|
|
// yet. Since the integration of a C function is very simple, as already
|
2023-02-18 17:39:21 -05:00
|
|
|
// seen in the last exercise, it naturally offers itself to use the
|
2023-03-30 09:40:13 -04:00
|
|
|
// very large variety of C functions for our own programs.
|
|
|
|
// As an example:
|
2023-02-18 17:39:21 -05:00
|
|
|
//
|
|
|
|
// Let's say we have a given angle of 765.2 degrees. If we want to
|
|
|
|
// normalize that, it means that we have to subtract X * 360 degrees
|
|
|
|
// to get the correct angle. How could we do that? A good method is
|
|
|
|
// to use the modulo function. But if we write "765.2 % 360", it won't
|
|
|
|
// work, because the standard modulo function works only with integer
|
2023-03-30 09:40:13 -04:00
|
|
|
// values. In the C library "math", there is a function called "fmod";
|
|
|
|
// the "f" stands for floating and means that we can solve modulo for
|
|
|
|
// real numbers. With this function, it should be possible to normalize
|
|
|
|
// our angle. Let's go.
|
2023-02-18 17:39:21 -05:00
|
|
|
|
|
|
|
const std = @import("std");
|
|
|
|
|
|
|
|
const c = @cImport({
|
2023-10-22 08:19:23 -04:00
|
|
|
// What do we need here?
|
2023-02-18 17:39:21 -05:00
|
|
|
???
|
|
|
|
});
|
|
|
|
|
|
|
|
pub fn main() !void {
|
2023-03-30 09:40:13 -04:00
|
|
|
const angle = 765.2;
|
2023-02-18 17:39:21 -05:00
|
|
|
const circle = 360;
|
|
|
|
|
2023-03-30 09:40:13 -04:00
|
|
|
// Here we call the C function 'fmod' to get our normalized angle.
|
|
|
|
const result = c.fmod(angle, circle);
|
2023-02-18 17:39:21 -05:00
|
|
|
|
2023-02-19 11:52:16 -05:00
|
|
|
// We use formatters for the desired precision and to truncate the decimal places
|
2023-03-30 09:40:13 -04:00
|
|
|
std.debug.print("The normalized angle of {d: >3.1} degrees is {d: >3.1} degrees.\n", .{ angle, result });
|
2023-02-18 17:39:21 -05:00
|
|
|
}
|