有没有一种方法可以在两列中显示我的素数列表输出

Is there a way to display my prime number list output in 2 columns?

本文关键字:显示 两列 我的 数列 输出 列表 一种 方法 有没有      更新时间:2023-10-16

我正在上我的第一堂编程课,这是我第一次发帖。当我陷入困境时,我已经能够在这个网站上为以前的项目找到帮助,我希望我做得对。

我已经完成了下面的程序,只显示0到100之间的素数,作为我对C++类的介绍。

唯一让我有点困扰的是,它在一列中,我想多走一步,让它看起来很漂亮,并在几列中显示数字。我试着用"\t",但我无法使它正常工作。有什么想法可以添加到我的代码中吗?我想我可以使用数组来完成,但我们还没有在课堂上讨论过,我还不应该使用它们。

挑战是:

"在一个文件中存储从1到100的所有素数列表的程序中,使用您在编程挑战21中编写的isPrime函数。"

这是我的代码:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
static int num1=0;
cout<<"Listed below is all prime numbers from 1 through 100."<<endl<<endl<<endl;
do
{
    num1++;
    if (isPrime(num1))
    {
    cout<<num1<<endl;
    }
}
while (num1<100);
cout<<endl;
return 0;
}
bool isPrime(int num1)
{
bool primeNum=true;
for (int i=2;i<num1;i++)
{
    if (num1%i==0)
    {
        primeNum=false;
    }
}
return primeNum;
}

提前感谢您的任何输入,

查找cout.width()

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
using namespace std;
bool isPrime(int);
int main()
{
    static int num1 = 0;
    cout << "Listed below is all prime numbers from 1 through 100." << endl << endl << endl;
    int column = 0; // column variable
    int width = 10; // column width size
    do
    {
        num1++;
        if (isPrime(num1))
        {
            cout.width(width); // set column's width
            cout << num1;
            if (column == 1) { // if prime number is printed in column 2
                cout << endl; // add new line
                column = 0; // set column to first
            }
            else {
                column++; // increase column index
            }
        }
    } while (num1<100);
    cout << endl;
    return 0;
}
bool isPrime(int num1)
{
    // error: your isPrime returns true when num1 is 1 or 2. change it
    if (num1 == 1 || num1 == 2) return false;
    // your isPrime
    bool primeNum = true;
    for (int i = 2; i<num1; i++)
    {
        if (num1%i == 0)
        {
            primeNum = false;
        }
    }
    return primeNum;
}

我刚刚意识到这个问题要求我将列表存储到文件中。所以我重写了一遍,这是我的新代码:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
bool isPrime(int);
int main()
{
int num=0;
cout<<"This Program will store a list of only the prime numbers "<<endl;
cout<<"between 0 and 100 to the text file "PrimeNumberList"."<<endl<<endl;
cout<<"Find the list by using the file explorer to search for "PrimeNumberList.txt"."<<endl;

ofstream outFile;
outFile.open("PrimeNumberList.txt");
if (outFile.fail())
{
    cout<<"Error opening "PrimeNumberList.txt" for output."<<endl;
    return 1;
}
for (int i=1;i<100;i++)
{
    if(isPrime(i))
    {
        outFile<<i<<endl;
    }
}
return 0;
}
bool isPrime(int num1)
{
if (num1==1)return false;
bool primeNum=true;
for (int i=2;i<num1;i++)
{
    if (num1%i==0)
    {
        primeNum=false;
    }
}
return primeNum;
}