Q:

Golang const, Type Casting | Find Output Programs | Set 2

belongs to collection: Golang Find Output Programs

0

This section contains the Golang const, Type Casting find output programs (set 2) with their output and explanations.

Program 1:

package main

import "fmt"

func main() {
    var num1 float32=3.146;
    var num2 int=0;
    
    num2 = (int)num1;
    
    fmt.Println(num2);  
}

Program 2:

package main

import "fmt"

func main() {
	var num1 string = "123"
	var num2 int = 0

	num2 = int(num1)

	fmt.Println(num2)
}

Program 3:

package main

import "fmt"
import "strconv"

func main() {
	var num1 string = "123.456"
	var num2 float64 = 0

	num2, _ = strconv.ParseFloat(num1, 64)

	fmt.Println(num2)
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

./prog.go:9:17: syntax error: unexpected num1 at end of statement

Explanation:

The above program will generate a syntax error because we cannot covert a floating-point number into an integer like this. The correct code is given below,

package main

import "fmt"

func main() {
	var num1 float32 = 3.146
	var num2 int = 0

	num2 = int(num1)

	fmt.Println(num2)
}

 

Answer Program 2:

Output:

./prog.go:9:12: cannot convert num1 (type string) to type int

Explanation:

The above program will generate a syntax error because we cannot covert numeric string into a number using the int() function. The correct code is given below,

package main

import "fmt"
import "strconv"

func main() {
	var num1 string = "123"
	var num2 int64 = 0

	num2, _ = strconv.ParseInt(num1, 0, 64)

	fmt.Println(num2)
}

 

Program 3:

Output:

123.456

Explanation:

 

In the above program, we converted a numeric string into a float point number using strconv.ParseFloat() function and print the result on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Find Output Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang for Loop | Find Output Programs | Set 1... >>
<< Golang const, Type Casting | Find Output Programs ...