You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

问题分析

你遇到的错误是因为a和b是字符串切片([]u8),本质是包含指针和长度的复合类型,Zig不允许直接对这类指针类型执行算术加法操作。要实现数值相加,必须先把输入的字符串转换成整数/浮点数类型。

修正方案

以下是实现整数相加的修正代码,包含字符串转数值、算术运算和结果输出的完整流程:

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_str = value.?;
    defer alloc.free(a_str);
    // 将字符串转为u32整数,若需要负数可改用i32
    const a = try std.fmt.parseInt(u32, a_str, 10);

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

    // 现在可以正常执行数值相加
    const tot = a + b;

    print("A = {d}\n", .{a});
    print("B = {d}\n", .{b});
    print("A + B = {d}\n", .{tot});
}
关键改动说明
  • 使用std.fmt.parseInt将输入的字符串转换为数值类型(示例中用u32无符号整数,根据需求可替换为i32/f64等)
  • 变量命名区分字符串原数据(a_str/b_str)和转换后的数值(a/b),避免混淆
  • 输出时使用{d}格式符打印整数,替代原代码中用于字符串的{s}

如果需要支持浮点数相加,只需把parseInt替换为parseFloat,并调整数值类型为f32或f64:

const a = try std.fmt.parseFloat(f64, a_str);
const b = try std.fmt.parseFloat(f64, b_str);
// 输出用{f}格式符
print("A + B = {f}\n", .{tot});

内容的提问来源于stack exchange,提问作者Aathiraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:30:08