Golang 程序读取数字 (n) 并计算 (n+nn+nnn)

go programmingserver side programmingprogramming更新于 2025/4/22 3:52:17

让我们读取一个数字,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

相关文章