094_c_math.zig 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // Often, C functions are used where no equivalent Zig function exists
  3. // yet. Okay, that's getting less and less. ;-)
  4. //
  5. // Since the integration of a C function is very simple, as already
  6. // seen in the last exercise, it naturally offers itself to use the
  7. // very large variety of C functions for our own programs.
  8. // As an example:
  9. //
  10. // Let's say we have a given angle of 765.2 degrees. If we want to
  11. // normalize that, it means that we have to subtract X * 360 degrees
  12. // to get the correct angle.
  13. // How could we do that? A good method is to use the modulo function.
  14. // But if we write "765.2 % 360", it only works with float values
  15. // that are known at compile time.
  16. // In Zig, we would use %mod(a, b) instead.
  17. //
  18. // Let us now assume that we cannot do this in Zig, but only with
  19. // a C function from the standard library. In the library "math",
  20. // there is a function called "fmod"; the "f" stands for floating
  21. // and means that we can solve modulo for real numbers. With this
  22. // function, it should be possible to normalize our angle.
  23. // Let's go.
  24. const std = @import("std");
  25. const c = @cImport({
  26. // What do we need here?
  27. ???
  28. });
  29. pub fn main() !void {
  30. const angle = 765.2;
  31. const circle = 360;
  32. // Here we call the C function 'fmod' to get our normalized angle.
  33. const result = c.fmod(angle, circle);
  34. // We use formatters for the desired precision and to truncate the decimal places
  35. std.debug.print("The normalized angle of {d: >3.1} degrees is {d: >3.1} degrees.\n", .{ angle, result });
  36. }