094_c_math.zig 1.3 KB

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