英文:
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.*;
这将正确地将a
和b
的值相加,并将结果存储在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
中的函数来进行解析:parseInt
、parseUnsigned
或 parseFloat
。
例如:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论