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

Golang新手求助:已传入参数但程序运行报错,求排查问题

Hey there! Let's walk through the issues in your Go code step by step—you're really close, just a few small gotchas with variable scoping and formatting that are tripping you up.

Key Issues & Fixes

1. Variable Shadowing (The Big One)

You declared outer variables like bj, ll, and dur at the top of main(), but then used := inside your if blocks to parse values. In Go, := creates new local variables in the current scope (the if block), not updates the outer ones. This means your outer variables stayed at their initial zero values, completely ignoring the parameters you passed in.

Fix this by separating the parsing and assignment:

// Instead of:
// if bj, err := strconv.ParseFloat(...); err != nil { ... }

// Do this:
temp, err := strconv.ParseFloat(os.Args[1], 32)
if err != nil {
    usageExit()
}
bj = float32(temp) // Assign to your outer float32 variable

2. Loop Variable Shadowing

Your for loop uses got := bj * (1.0 + ll)—again, this creates a new got variable inside the loop every iteration, leaving your outer got untouched. Plus, your logic looks like it's meant to calculate compound interest, so you need to update got incrementally:

got = bj // Start with the principal value
for i := 0; i < dur; i++ {
    got = got * (1.0 + ll) // Compound the value each period
}

3. Wrong Print Function

You used fmt.Print("Result: %f", got)—fmt.Print doesn't process format placeholders like %f. Use fmt.Printf instead to properly format your float:

fmt.Printf("Result: %.2f\n", got) // %.2f rounds to 2 decimal places for readability

4. Missing checkParam & usageExit Implementations

I assume these functions are defined elsewhere, but to make the code complete, here's a quick implementation for context:

func usageExit() {
    fmt.Println("Usage: ./your-program <principal> <interest-rate> <duration>")
    os.Exit(1)
}

func checkParam(args []string) {
    // os.Args[0] is the program name, so we need 3 user arguments
    if len(args) != 4 {
        usageExit()
    }
}

Full Fixed Code

package main

import (
    "fmt"
    "os"
    "strconv"
)

func usageExit() {
    fmt.Println("Usage: ./compound <principal> <interest-rate> <duration>")
    os.Exit(1)
}

func checkParam(args []string) {
    if len(args) != 4 {
        usageExit()
    }
}

func main() {
    checkParam(os.Args)
    var got, bj, ll float32
    var dur int

    // Parse principal
    temp, err := strconv.ParseFloat(os.Args[1], 32)
    if err != nil {
        usageExit()
    }
    bj = float32(temp)

    // Parse interest rate (use decimal form, e.g., 0.05 for 5%)
    temp, err = strconv.ParseFloat(os.Args[2], 32)
    if err != nil {
        usageExit()
    }
    ll = float32(temp)

    // Parse duration
    dur, err = strconv.Atoi(os.Args[3])
    if err != nil {
        usageExit()
    }

    // Calculate compound interest
    got = bj
    for i := 0; i < dur; i++ {
        got = got * (1.0 + ll)
    }

    fmt.Printf("Result: %.2f\n", got)
}

Quick Note

Make sure your interest rate is passed as a decimal (e.g., 0.05 for 5%)—if you want users to pass percentages like 5, just add ll = ll / 100 after parsing the rate.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:38:57