首页 > 解决方案 > 如何以五个数字的行显示输出?

问题描述

我是编程新手,我必须以五行显示作为此代码乘积的所有质数。经过太多小时试图在网上找到一些东西,这就是我想出的。这样,最后连质数都不会显示;一路只有1s。我很高兴知道我做错了什么或者我可以改变什么。

#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;
}

标签: c++loopsvectorcounterprimes

解决方案


您正在严重过度复杂化您的输出逻辑。只需在执行输出counter的循环外部声明一个变量(并初始化为零)for,然后每次打印一个数字时,将其递增。当它达到 5 的值时,打印一个换行符并将其重置为零。

其他几点:

  1. STL 容器(如std::vector)使用类型size_t不是int)作为它们的大小和索引。int在下面的代码中,我已将您的所有变量都更改为这种类型;幸运的是,这不会影响您的算法。

  2. 请注意,1 不是质数

这是您的代码的重新处理版本:

#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;
}

推荐阅读