diff options
| author | Chris Boesch <chrboesch@noreply.codeberg.org> | 2026-04-03 19:32:53 +0200 |
|---|---|---|
| committer | Chris Boesch <chrboesch@noreply.codeberg.org> | 2026-04-03 19:32:53 +0200 |
| commit | 5307b2a338a92130bc498fb1dc7d21a9fd1b0db4 (patch) | |
| tree | 51279ca4fbd7bd90294dd563640c12a8c25c79c6 /exercises/097_c_math.zig | |
| parent | 3056a2b5442f2f1ec58db3f3493109064ad2a2a5 (diff) | |
| parent | f6a6798c8b6b813bd2ceee81db276e05327a76e0 (diff) | |
Merge pull request 'revival of the async-io functions' (#383) from asyncIo into main
Reviewed-on: https://codeberg.org/ziglings/exercises/pulls/383
Diffstat (limited to 'exercises/097_c_math.zig')
| -rw-r--r-- | exercises/097_c_math.zig | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/exercises/097_c_math.zig b/exercises/097_c_math.zig new file mode 100644 index 0000000..ec59a86 --- /dev/null +++ b/exercises/097_c_math.zig @@ -0,0 +1,41 @@ +// +// Often, C functions are used where no equivalent Zig function exists +// yet. Okay, that's getting less and less. ;-) +// +// Since the integration of a C function is very simple, as already +// seen in the last exercise, it naturally offers itself to use the +// very large variety of C functions for our own programs. +// As an example: +// +// 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 only works with float values +// that are known at compile time. +// In Zig, we would use @mod(a, b) instead. +// +// Let us now assume that we cannot do this in Zig, but only with +// a C function from the standard library. In the 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. + +const std = @import("std"); + +const c = @cImport({ + // What do we need here? + ??? +}); + +pub fn main() !void { + const angle = 765.2; + const circle = 360; + + // Here we call the C function 'fmod' to get our normalized angle. + const result = c.fmod(angle, circle); + + // We use formatters for the desired precision and to truncate the decimal places + std.debug.print("The normalized angle of {d: >3.1} degrees is {d: >3.1} degrees.\n", .{ angle, result }); +} |
