在 Perl 中,如果我想执行 shell 命令,例如foo,我会这样做:
#!/usr/bin/perl
$stdout = `foo`
Run Code Online (Sandbox Code Playgroud)
在 Python 中,我发现了这个非常复杂的解决方案:
#!/usr/bin/python
import subprocess
p = subprocess.Popen('foo', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = p.stdout.readlines()
retval = p.wait()
Run Code Online (Sandbox Code Playgroud)
有没有更好的解决方案?
请注意,我不想使用callor os.system。我想stdout放在一个变量上
我试图使用 java 的整数除法,据说它需要发言。但是,它向零而不是地板四舍五入。
public class Main {
public static void main(String[] args) {
System.out.println(-1 / 100); // should be -1, but is 0
System.out.println(Math.floor(-1d/100d)); // correct
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我不想转换为双精度/浮点数,因为它需要高效。我试图用一种方法来解决这个问题,floorDivide(long a, long b). 我所拥有的是:
static long floorDivide(long a, long b) {
if (a < 0) {
// what do I put here?
}
return a / b;
}
Run Code Online (Sandbox Code Playgroud)
如果没有双精度/浮点数,我怎么能做到这一点?
请考虑以下代码:
import java.awt.*;import javax.swing.*;import javax.swing.text.*;
public class Main extends JFrame {
private final StyleContext cont = StyleContext.getDefaultStyleContext();
private final AttributeSet normal = cont.addAttribute(cont.getEmptySet(),StyleConstants.Foreground,Color.BLACK);
private final AttributeSet bold = cont.addAttribute(cont.getEmptySet(),StyleConstants.Bold,Color.BLACK);
public Main() {
setSize(800,600);
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout()); // this is used to make the textpane take up the entire space
getContentPane().add(pane); // adds pane to the frame
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
try {
doc.insertString(0,"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",normal/*change to …Run Code Online (Sandbox Code Playgroud)