mirror of
https://codeberg.org/andyscott/ziglings.git
synced 2024-11-09 11:40:46 -05:00
added C math exercise
This commit is contained in:
parent
6353299cd6
commit
23f2cc88d2
4 changed files with 44 additions and 2 deletions
|
@ -471,7 +471,12 @@ const exercises = [_]Exercise{
|
|||
},
|
||||
.{
|
||||
.main_file = "093_hello_c.zig",
|
||||
.output = "Hello C from Zig! - C result ist 17 chars",
|
||||
.output = "Hello C from Zig! - C result ist 17 chars written.",
|
||||
.C = true,
|
||||
},
|
||||
.{
|
||||
.main_file = "094_c_math.zig",
|
||||
.output = "The normalized angle of 765.2 degrees is 45.2 degrees.",
|
||||
.C = true,
|
||||
},
|
||||
.{
|
||||
|
|
|
@ -57,7 +57,7 @@ pub fn main() void {
|
|||
const c_res = write(2, "Hello C from Zig!", 17);
|
||||
|
||||
// let's see what the result from C is:
|
||||
std.debug.print(" - C result ist {d} chars\n", .{c_res});
|
||||
std.debug.print(" - C result ist {d} chars written.\n", .{c_res});
|
||||
}
|
||||
//
|
||||
// Something must be considered when compiling with C functions.
|
||||
|
|
33
exercises/094_c_math.zig
Normal file
33
exercises/094_c_math.zig
Normal file
|
@ -0,0 +1,33 @@
|
|||
//
|
||||
// Often C functions are used where no equivalent Zig function exists
|
||||
// yet. 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 the own programs.
|
||||
// In addition immediately 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 won't
|
||||
// work, because the standard modulo function works only with integer
|
||||
// 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 angel. Let's go.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const c = @cImport({
|
||||
// What do wee need here?
|
||||
???
|
||||
});
|
||||
|
||||
pub fn main() !void {
|
||||
const angel = 765.2;
|
||||
const circle = 360;
|
||||
|
||||
// Here we call the C function 'fmod' to get our normalized angel.
|
||||
const result = c.fmod(angel, circle);
|
||||
|
||||
std.debug.print("The normalized angle of {d: >3.1} degrees is {d: >3.1} degrees.\n", .{ angel, result });
|
||||
}
|
4
patches/patches/094_c_math.patch
Normal file
4
patches/patches/094_c_math.patch
Normal file
|
@ -0,0 +1,4 @@
|
|||
22c22
|
||||
< ???
|
||||
---
|
||||
> @cInclude("math.h");
|
Loading…
Reference in a new issue