- 1

Challenge 3.2 Add to cart / Shopping Cart

Hi guys, I am trying to solve the following challenge, but I think I am making a mistake in the use of the object instance. Does anyone have any hint for my problem? The problem Statement is the following: . Shopping Cart You are building a Shopping Cart. It is represented by a Cart struct, which holds the item prices in an array called prices. Your program needs to take the number of items as input, followed by the prices of the items. Initialize a Cart of that size, and add the prices to the Cart's array. After that, call the Cart's show() method. The show() method should output the total cost of the cart. The given code includes comments as instructions. Use a normal loop to take the inputs, and a range loop to calculate the sum of all prices. Also, note that the prices are floats. .

28th May 2021, 1:45 AM
Lucas Kliemczak
Lucas Kliemczak - avatar
4 odpowiedzi
+ 3
I did this in a loop to get input, m is a float32: fmt.Scanln(&m) c.prices = append(c.prices, m)
5th Sep 2021, 2:12 PM
Paul
Paul - avatar
0
Lucas answer (below) is almost correct, but "int" type in "a" slice should be "float32" and then need to loop through the "a" slice and append each number to c.prices
28th Oct 2021, 9:56 PM
Egor Geisik
Egor Geisik - avatar
0
This is my final solution. I've struggled with the for loop in the main function but after I saw the advice from above, my problem was fixed with ease. package main import "fmt" type Cart struct { prices []float32 } func (x Cart) show() { var sum float32 = 0.0 //calculate the sum of all prices in the Cart for _, i := range x.prices { sum += i } fmt.Println(sum) } func main() { c := Cart{} var n int fmt.Scanln(&n) var price float32 // take n inputs and add them to the Cart for i := 0; i < n; i ++ { fmt.Scanln(&price) c.prices = append(c.prices, price) } c.show() }
26th Dec 2021, 6:40 PM
Georgi Valkanov
Georgi Valkanov - avatar
- 1
The pre written code combined with my implementation is the following: . package main import "fmt" type Cart struct { prices []float32 } func (x Cart) show() { var sum float32 = 0.0 //calculate the sum of all prices in the Cart for _,p := range x.prices{ sum += p } //------------------------------------------- fmt.Println(sum) } func main() { c := Cart{} var n int fmt.Scanln(&n) // take n inputs and add them to the Cart a := make([]int, n) for i := range a{ fmt.Scanln(&a[i]) } //call the show() method of the Cart c.show() }
28th May 2021, 4:04 PM
Lucas Kliemczak
Lucas Kliemczak - avatar