Zig-Fak-Calc/fakultaetsCalc.zig

52 lines
1.4 KiB
Zig
Raw Permalink Normal View History

2024-10-13 23:09:14 +02:00
2024-10-11 01:54:22 +02:00
const std = @import("std");
pub fn main() !void {
const reader = std.io.getStdIn().reader();
const writer = std.io.getStdOut().writer();
2024-10-13 23:09:14 +02:00
2024-10-11 01:54:22 +02:00
const userNumberInput: u128 = try getInputNumber(writer, reader);
const calcedFact = try calcFact(userNumberInput);
try writer.print("Calculated number: {d}\n", .{calcedFact});
}
pub fn getInputNumber(writer: anytype, reader: anytype) !u128 {
var buffer: [256]u8 = undefined;
while (true) {
try writer.print("Enter a number \n", .{});
try writer.print("> ", .{});
const amountInputBytes = try reader.read(&buffer);
const input_slice = buffer[0..(amountInputBytes - 1)];
const result = std.fmt.parseInt(u128, input_slice, 10) catch |err| {
switch (err) {
error.InvalidCharacter => {
try writer.print("Error: Invalid character in input.\n", .{});
},
error.Overflow => {
try writer.print("Error: Too large.\n", .{});
},
}
try writer.print("\n", .{});
continue;
};
return result;
}
}
pub fn calcFact(maxNum: u128) !u128 {
if (maxNum == 0) {
return 1;
}
const multValue: u128 = try calcFact(maxNum - 1);
return (maxNum * multValue);
}
// Bei start wird Zufallszahl gewählen
// Nutzer sucht dann manuel mit binary search nach der zahl