Golang 程式讀取一個數字 (n) 並計算 (n+nn+nnn)


讓我們讀取一個數字,n=5

然後,nn=55,然後 nnn=555

res = 5 + 55 + 555 => 615

若要讀取一個數字 (n) 並計算 (n+nn+nnn),我們可以採取以下

步驟


  • 定義一個變數 n。
  • 列印一個語句以獲取數字 n。
  • 獲取使用者對變數 n 的輸入。
  • 為 (n + nn + nnn) 建立一個表示式。
  • 將表示式轉化為數字。
  • 計算表示式的總和。

示例

 即時演示

package main
import (
   "fmt"
   "strconv"
)
func main(){
   var n int
   fmt.Print("Enter value of n: ")
   fmt.Scanf("%d", &n)
   t1 := fmt.Sprintf("%d", n)
   t2 := fmt.Sprintf("+%d%d", n, n)
   t3 := fmt.Sprintf("+%d%d%d", n, n, n)
   exp := t1 + t2 + t3
   fmt.Println("Expression is: ", exp)
   n1, _ := strconv.Atoi(t1)
   n2, _ := strconv.Atoi(t2)
   n3, _ := strconv.Atoi(t3)
   fmt.Println("Computed expression is: ", n1+n2+n3)
}

輸出

Enter value of n: 5
Expression is: 5+55+555
Computed expression is: 615

更新於: 31-7-2021

265 次瀏覽

開始您的 職業生涯

完成課程以獲得認證

開始學習
廣告