如何在Zig语言中将两个用户输入的整数值相加?

huangapple go评论51阅读模式
英文:

How to add two user input integer values in ziglang?

问题

在Zig编程语言中,您遇到了一个错误。错误信息显示在这两行代码上:

alloc.zig:17:19: error: invalid operands to binary expression: 'Pointer' and 'Pointer'
const tot = a + b;

这个错误是因为您尝试将两个指针相加,而不是它们指向的实际值。为了将两个变量相加并将结果存储在单个变量中,您需要解引用这些指针。在Zig中,您可以使用.*来解引用指针。这里是修复后的代码片段:

const tot = a.* + b.*;

这将正确地将ab的值相加,并将结果存储在tot中。

英文:

I have written a program that takes two values and sums them up and then displays them as a single value.

but if add those two values it erroring in ziglang

const std = @import("std");

const print = std.debug.print;
const stdin = std.io.getStdIn().reader();

var buff: [1000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buff);
const alloc = fba.allocator();

pub fn main() !void {
    print("Enter value for A: ", .{});
    const value = try stdin.readUntilDelimiterOrEofAlloc(alloc, '\n', 100);
    const a = value.?;
    defer alloc.free(a);

    print("Enter value for B: ", .{});
    const value1 = try stdin.readUntilDelimiterOrEofAlloc(alloc, '\n', 10);
    const b = value1.?;
    defer alloc.free(b);

    const tot = a + b;

    print("A = {s}\n", .{a});
    print("B = {s}\n", .{b});
    print("A + B = {s}\n", .{tot});

error message:

alloc.zig:17:19: error: invalid operands to binary expression: 'Pointer' and 'Pointer'
    const tot = a + b;

I want to add two variables and to store into single variable

答案1

得分: 2

你必须首先解析从 readUntilDelimiterOrEofAlloc 获取的字符串为数字。你可以使用 std.fmt 中的函数来进行解析:parseIntparseUnsignedparseFloat

例如:

const value_a = try std.fmt.parseInt(i64, a, 10);
const value_b = try std.fmt.parseInt(i64, b, 10);
const sum = value_a + value_b;
print("{} + {} = {}\n", .{value_a, value_b, sum});

示例输出:

$ zig build run
Enter value for A: 123
Enter value for B: 111
123 + 111 = 234
英文:

You must first parse the strings you get from readUntilDelimiterOrEofAlloc into numbers. You can use functions from std.fmt for that: parseInt, parseUnsigned or parseFloat.

For example:

const value_a = try std.fmt.parseInt(i64, a, 10);
const value_b = try std.fmt.parseInt(i64, b, 10);
const sum = value_a + value_b;
print("{} + {} = {}\n", .{value_a, value_b, sum});

Example output:

$ zig build run
Enter value for A: 123
Enter value for B: 111
123 + 111 = 234

huangapple
  • 本文由 发表于 2023年3月31日 21:06:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定