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 次浏览

开始您的 职业生涯

完成课程以获得认证

开始学习
广告
© . All rights reserved.