使用新行打印执行流程

时间:2018-04-12 16:43:21

标签: if-statement go conditional

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    } else {
        fmt.Printf("%g >= %g\n", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

此代码来自“GO之旅”

期望:

9   
10   
27 >= 20     
20

输出:

27 >= 20    
9 20

我不明白这一点。帮助我!

2 个答案:

答案 0 :(得分:1)

Println函数将在一行中输出两个pow函数,然后在从Println函数返回后添加\n

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    }else {
        fmt.Printf("%g >= %g\n", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(pow(3, 2, 10))
    fmt.Println(pow(3, 3, 20))
}

Playground

10这是第一个限制,如果不会打印的情况。

9
10
27 >= 20
20

因为在函数之前返回了pow函数。

答案 1 :(得分:1)

首先评估参数,pow内的if位于Println块中,以便有条件地运行。

首先,评估main()pow的参数。第一次调用9会导致lim小于pow,因此9本身不打印任何内容并返回pow。第二次调用27会导致lim大于pow,因此27 >= 20会打印20并返回Println。然后,处理完参数后,执行main中9 20的调用,打印import java.awt.*; import javax.swing.*; import javax.swing.border.Border; import java.awt.Color; import java.awt.Graphics; public class Circle extends JPanel { public static JFrame frameOne = new JFrame("Frame 1"); public static Circle boardSquares[][] = new Circle[8][8]; public static void main(String[] args) { checkerBoard(); frameOne.setSize(new Dimension(400,400)); frameOne.getContentPane().setLayout(new GridLayout(8,8,0,0)); frameOne.setBackground(Color.BLACK); frameOne.setVisible(true); frameOne.setResizable(false); frameOne.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); boardSquares[1][1].setChecker(true); } private Color c; private boolean checker; public Circle(int i, int j) { super(); //setBorder(new Border()); //set if ((i + j) % 2 == 0) { c = Color.DARK_GRAY; } else { c = Color.WHITE; } } void setChecker(boolean ch) { checker = ch; } public static void checkerBoard() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { boardSquares[i][j] = new Circle(i, j); frameOne.add(boardSquares[i][j]); } } } public void paintComponent(Graphics g) { g.setColor(c); g.fillRect(0, 0, 40, 40); if (checker) { g.setColor(Color.BLUE); g.fillOval(4, 4, 32, 32); } }