Section11-5
This commit is contained in:
@@ -15,3 +15,18 @@ Coding Exercise #3
|
||||
|
||||
7. Print out the nums slice
|
||||
*/
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
nums := []float64{1.1, 2.1, 3.1}
|
||||
nums = append(nums, 10.1)
|
||||
fmt.Println(nums)
|
||||
nums = append(nums, 4.1, 5.5, 6.6)
|
||||
fmt.Println(nums)
|
||||
|
||||
n := []float64{8.1, 9.3}
|
||||
nums = append(nums, n...)
|
||||
fmt.Println(nums)
|
||||
}
|
||||
|
||||
58
Section11/89-4.go
Normal file
58
Section11/89-4.go
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
Create a Go program that reads some numbers from the command line and then
|
||||
calculates the sum and the product of all the numbers given at the command line.
|
||||
|
||||
The user should give between 2 and 10 numbers.
|
||||
|
||||
Notes:
|
||||
|
||||
- the program should be run in a terminal (go run main.go) not in Go Playground
|
||||
|
||||
- example:
|
||||
|
||||
go run main.go 3 2 5
|
||||
|
||||
Expected output: Sum: 10, Product: 30
|
||||
*/
|
||||
|
||||
// run this program in a terminal with arguments
|
||||
// ex: go run main.go 5 7.1 9.9 10
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
if len(os.Args) < 2 { //if not run with arguments
|
||||
log.Fatal("Please run the program with arguments (2-10 numbers)!")
|
||||
|
||||
}
|
||||
|
||||
//taking the arguments in a new slice
|
||||
args := os.Args[1:]
|
||||
|
||||
// declaring and initializing sum and product of type float64
|
||||
sum, product := 0., 1.
|
||||
|
||||
if len(args) < 2 || len(args) > 10 {
|
||||
fmt.Println("Please enter between 2 and 10 numbers!")
|
||||
} else {
|
||||
|
||||
for _, v := range args {
|
||||
num, err := strconv.ParseFloat(v, 64)
|
||||
if err != nil {
|
||||
continue //if it can't convert string to float64, continue with the next number
|
||||
}
|
||||
sum += num
|
||||
product *= num
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("Sum: %v, Product: %v\n", sum, product)
|
||||
}
|
||||
24
Section11/89-5.go
Normal file
24
Section11/89-5.go
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
Consider the following slice declaration:
|
||||
nums := []int{5, -1, 9, 10, 1100, 6, -1, 6}
|
||||
|
||||
Using a slice expression and a for loop iterate over
|
||||
the slice ignoring the first and the last two elements.
|
||||
|
||||
Print those elements and their sum.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
nums := []int{5, -1, 9, 10, 1100, 6, -1, 6}
|
||||
sum := 0
|
||||
for _, v := range nums[2 : len(nums)-2] {
|
||||
fmt.Println(v)
|
||||
sum += v
|
||||
}
|
||||
fmt.Println("Sum:", sum)
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user