C++原理和练习练习-从输入值n中寻找素数

C++ Priciples and Practice Exercise - Finding primes from input value n

本文关键字:练习 寻找 C++ 输入      更新时间:2023-10-16

找到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 primesn";
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;
}

我很难理解的两件事:

  1. 为什么顶部有一段代码在int main之外,是在int main之后执行的吗
  2. 这些语句是如何工作的(它们是双重条件吗?(bool prime (vector<int> table, int number)if (prime(table,next))

谢谢,Sean

您所问的问题对于C和C++语言来说是非常基础的。阅读任何一本好的C++教材的前2-3章都会为你回答这些问题。

示例代码定义了2个函数:primemain

  1. main之外的代码是prime函数的定义。它是定义的(创建(,供您稍后在main函数中调用
  2. 这是两件独立的事情。您提到的第一件事是函数prime的定义,第二件事是对该函数的调用