找到 Stroustrups 初学者书籍 Ch4Ex15 的这个答案,问题是找到前 n 个素数:
#include "std_lib_facilities.h"
bool prime (vector<int> table, int number) {
for (int i = 0; i < table.size(); ++i)
if (number%table[i] == 0) return false;
return true;
}
int main () {
int count, next;
cout << "Input the number of primes\n";
cin >> count;
vector<int> table;
next = 2;
while (table.size() < count) {
if (prime(table,next)) table.push_back(next);
++next;
}
for (int n = 0; n < table.size(); ++n)
cout << table[n] << " ";
cout << endl;
// keep_window_open();
return 0;
}
我很难理解的两件事:
- 为什么顶部有一段代码在int main之外,是在int main之后执行的吗?
- 这些语句是如何工作的(它们是双重条件吗?)
bool prime (vector<int> table, int number)
和if (prime(table,next))
谢谢,肖恩