golan为输入的整数创建平方和的输出



我创建了一个计算器,用于计算给定整数(不包括任何负数)的平方和。

我面临的问题是,我想让输出显示当我完成输入所有的输入。例如,

样本输入:

2
4
3 -1 1 14
5
9 6 -53 32 16

示例输出:

206
1397

相反,当第一种情况的输出结束时,第一种情况将以在我完成所有输入之前给出输出的形式自动计算。如何在接收到所有输入之前不显示输出?

// Calculate the sum of squares of given integers, excluding any negatives In Go lang
// Code written by Pintu Sharma
// Enter Total number of test cases := N
// N Times :
// Enter Total number of values.    := num
// Enter [num] times int values
// sample input:
// 2
// 4
// 3 -1 1 14
// 5
// 9 6 -53 32 16
// sample output :
// 206
// 1397

// sum of square, only positive numbers without using any loop
// Thats why i use recurssion in Go
// my Code in Go lang
package main
import "fmt"
// Taking Number of Test Cases and values
func test_cases(n int) {
if n <= 0 {
return
}
var num int
// total number of values
fmt.Scanf("%d", &num)
fmt.Println(sum_of_square(num))
test_cases(n-1)
}
// Calculating sum of square for each test case
func sum_of_square(value_count int) int {
if value_count == 0 {
return 0
}
var value int
// take input value for generating sum of square
fmt.Scanf("%d", &value)
// if only value is positive
if value > 0 {
return value*value + sum_of_square(value_count - 1)
}
return sum_of_square(value_count - 1)
}
// Main function
func main() {
var N int
// number of total Test Cases
fmt.Scanf("%d", &N)
// Take input for each Test Case
test_cases(N)
}

您可以在递归调用中读取该值后打印该值。

func sum_of_square(value_count int) int {
if value_count == 0 {
fmt.Println()
return 0
}
var value int
// take input value for generating sum of square
fmt.Scanf("%d", &value)
// if only value is positive
fmt.Print(strconv.Itoa(value) + " ")
if value > 0 {
return value*value + sum_of_square(value_count - 1)
}
return sum_of_square(value_count - 1)
}

语句fmt.Scanf("%d", &value)在读取值后打印该值。在读取所有值后,fmt.Println()将添加一个新行。

最新更新