我是编程新手,我必须以五行的形式显示此代码乘积的所有素数。经过几个小时的尝试在网上寻找一些东西后,这就是我想到的。这样,最后连质数都没有显示出来;全程只有1秒。我很高兴知道我做错了什么或者我可以改变什么。
#include <iomanip>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main() {
int n { 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool> cygnus(n + 1);
for (int m = 0; m <= n; m++) {
cygnus[m]=true;
}
for (int j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (int i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
int s = 0;
for (auto value : cygnus) {
if (value == true && s > 0) {
for (int counter = s; counter++; ) {
if (counter % 5 == 0) {
cout << setw(3) << s << " \n ";
}
if (counter % 5 != 0) {
cout << setw(3) << s << " ";
}
}
}
s++;
}
cout << endl;
return 0;
}
最佳答案
您的输出逻辑严重过度复杂化。只需在执行输出的 for
循环外部声明一个 counter
变量(并初始化为零),然后每次打印数字时,递增它。当该值达到 5 时,打印换行符并将其重置为零。
其他几点:
STL 容器(如
std::vector
)使用 thesize_t
type (不是int
)它们的大小和索引。在下面的代码中,我已将所有int
变量更改为这种类型;幸运的是,这不会影响您的算法。
这是代码的重新编写版本:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
size_t n{ 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool>cygnus(n + 1);
for (size_t m = 0; m <= n; m++) {
cygnus[m] = true;
}
for (size_t j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (size_t i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
size_t s = 0;
size_t counter = 0;
for (auto value : cygnus) {
if (value == true && s > 1) { // Note that 1 is NOT a prime number
cout << setw(3) << s << " ";
if (++counter == 5) {
cout << "\n ";
counter = 0;
}
}
s++;
}
if (counter != 0) cout << "\n "; // Add newline for any partial last line.
cout << endl;
return 0;
}
关于c++ - 如何以五个数字的行显示输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69700210/