如何在Go语言中不使用for语句实现正整数平方和计算?
How to Calculate Sum of Squares (Excluding Negatives) in Go Without Using
for Statements Hey there! I see you've already got a working implementation using for loops, but since the requirement bans for statements, recursion is our perfect alternative here—it’s a clean way to replace iterative logic without relying on loops, and we can stick strictly to Go’s standard library.
The Approach
We’ll use recursive functions to handle two layers of iteration:
- A recursive function to process each of the N test cases one by one.
- Another recursive function to read X numbers per test case, calculate the sum of squares for non-negative values, and return the total.
Compliant Go Implementation
package main import "fmt" // processTestCases handles N test cases recursively func processTestCases(n int) { if n <= 0 { return } var x int fmt.Scan(&x) sum := calculateSum(x) fmt.Println(sum) processTestCases(n - 1) } // calculateSum reads x numbers and returns sum of squares of positive values func calculateSum(x int) int { if x <= 0 { return 0 } var y int fmt.Scan(&y) current := 0 // Match your original logic: only include positive numbers (exclude negatives and zero) if y > 0 { current = y * y } return current + calculateSum(x - 1) } func main() { var n int fmt.Scan(&n) processTestCases(n) }
Verify with Your Example Input
Input:
2 4 3 -1 1 14 5 9 6 -53 32 16
Output:
206 1397
This matches exactly the expected result from your original code!
Key Changes from Your Original Code
- Replaced the outer
forloop (processing N test cases) withprocessTestCases: we keep calling the function withn-1until we’ve handled all test cases. - Replaced the inner
forloop (reading X numbers) withcalculateSum: each call reads one number, adds its square if it’s positive, then recurses withx-1until all X numbers are processed. - We’re still only using the
fmtstandard library, so we meet the "仅用标准库" requirement perfectly.
Quick Edge Case Note
If you need to include zero in the sum (since the problem mentions "非负整数"), just adjust the condition in calculateSum to y >= 0—the code is easy to tweak here to match exact requirements.
内容的提问来源于stack exchange,提问作者w0lf
相关产品推荐
相关产品推荐

