C++ 原理与实践练习 - 从输入值 n 中寻找素数
C++ Priciples and Practice Exercise - Finding primes from input value n
找到了 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))
谢谢,
肖恩
你问的问题是 C 和 C++ 语言的基础。通读任何一本优秀的 C++ 教科书的前 2-3 章都会为您解答这些问题。
示例代码定义 2 个函数:prime
和main
。
main
之外的代码是prime
函数的 定义。它是 defined(已创建)供您稍后在 main
函数中调用。
- 这是两个不同的东西。您提到的第一件事是函数
prime
的定义,第二件事是对该函数的 调用 。
找到了 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))
谢谢, 肖恩
你问的问题是 C 和 C++ 语言的基础。通读任何一本优秀的 C++ 教科书的前 2-3 章都会为您解答这些问题。
示例代码定义 2 个函数:prime
和main
。
main
之外的代码是prime
函数的 定义。它是 defined(已创建)供您稍后在main
函数中调用。- 这是两个不同的东西。您提到的第一件事是函数
prime
的定义,第二件事是对该函数的 调用 。