小编Dom*_*ndo的帖子

做循环与Java中的循环计数

在计数方面,应该使用do-while循环还是for循环?因为这:

class Main {
  public static void main(String[] args) {
    int times = 1;
    do {
      System.out.println("I have printed " + times + " times.");
      times++;
    } while (times < 6);
  }
}
Run Code Online (Sandbox Code Playgroud)

似乎与此完全相同:

class Main {
  public static void main(String[] args) {
    for (int times = 1; times < 6; times++) {
      System.out.println("I have printed " + times + " times.");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是速度的差异吗?偏爱?情况?个人怪癖?某种"Java社会禁忌"?我不知道.似乎可以用于有效计数,只需要更多.两者都打印完全相同的东西.

System.out.println("Many thanks!!");

java for-loop counting do-while

9
推荐指数
1
解决办法
415
查看次数

在C++中暂停 - 哪种方法?

我注意到有两种不同的方法可以在C++中"暂停".(虽然我认为它的正确名称是sleep.)

方法1,(可能是最熟悉的方法):

#include <iostream>
#include <unistd.h>
int main() {
  std::cout<<"Hello, "<<std::endl;
  sleep(1);
  std::cout<<"world!\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我首先学到的方法:

#include <iostream>
#include <thread>
#include <chrono>
int main() {
  std::cout<<"Hello, "<<std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout<<"world!\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我不是问哪条路是对的,(它们都做同样的事情),而是我要问哪个更常用,或者"接受".另外,这两者在速度/性能等方面有区别吗?

c++ sleep thread-sleep

4
推荐指数
1
解决办法
867
查看次数

Java - Catch Exception e

e以下代码的含义是什么?

try {
    // Do something
} catch (Exception e) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

我一直在研究,一无所获.

System.out.println("Thanks!");

java exception try-catch

0
推荐指数
1
解决办法
495
查看次数

在C++中声明函数时,是否需要具有函数本身的参数?

(请记住,我最近才深入研究C++函数.)
假设你想要一个从1到特定数字的函数.

#include <iostream>
int countTo(int num);
int countTo(int num) {
  for (int i = 1; i <= num; i++) {
    std::cout << i << "\n";
  }
  return num;
}
int main() {
  int num;
  std::cout << "Enter a number to which the program will count: ";
  std::cin >> num;
  countTo(num);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我把相同的代码放到编译器中,只是没有函数声明中的参数,如下所示:

int countTo();
int countTo(int num) {
  for (int i = 1; i <= num; i++) {
    std::cout << i << "\n";
  }
  return …
Run Code Online (Sandbox Code Playgroud)

c++ function

-1
推荐指数
1
解决办法
58
查看次数

在|之间放置变量 | 在Ruby中

在Ruby代码中,我注意到其间放置了一些变量或其他对象| |.我不知道为什么.它通常用在哈希映射中吗?

ruby variables

-4
推荐指数
1
解决办法
57
查看次数