【问题标题】:How to display output in rows of five numbers?如何以五个数字的行显示输出?
【发布时间】:2021-12-10 11:24:39
【问题描述】:

我是编程新手,我必须以五行显示所有作为此代码乘积的素数。经过太多小时试图在网上找到一些东西,这就是我想出的。这样,最后连质数都不会显示;一路只有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;
}

【问题讨论】:

  • 附注:m&lt;n 而不是 m&lt;=n 在“for”测试中,i&lt;=n 相同,否则您试图访问数组中超出范围的索引。
  • 最适合您的情况是使用调试器在应用程序运行时检查值。如果您不使用调试器,请在任何地方放置很多带有您要检查的值的“cout”,以便查看发生了什么。
  • @Ripi2 实际上,我刚刚注意到:向量是用n + 1 元素初始化的,所以m&lt;=n 是可以的。我在回答中犯了同样的错误,我将更正。

标签: c++ loops vector counter primes


【解决方案1】:

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

其他几点:

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

  2. 注意that 1 is not a prime number

这是您的代码的修改版本:

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

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2021-03-08
    • 2012-06-04
    • 2013-03-21
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多