有没有办法在2列中显示我的素数列表输出?

时间:2015-04-10 02:34:22

标签: c++ visual-studio-2012

我正在参加我的第一次编程课程,这是我第一次发帖。当我遇到困难时,我已经能够在以前的项目中找到这个网站的帮助,我希望我做得对。

我已经完成了下面的程序,只显示0到100之间的素数,用于我的C ++类简介。

唯一让我感到困扰的是它在一个列中,我想要采取额外的步骤,让它看起来很漂亮并在几列中显示数字。我尝试使用“\ t”,但我无法让它正常工作。关于我可能添加到代码中的任何想法?    我想我可以使用一个数组来完成它,但我们没有在课堂上介绍它,我不应该使用它们。

挑战是:

“使用您在编程挑战21中编写的isPrime函数,该程序存储文件中1到100之间所有素数的列表。”

这是我的代码:

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

提前感谢任何输入,

2 个答案:

答案 0 :(得分:1)

查找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;
}

答案 1 :(得分:0)

我刚刚意识到要求我 STORE 将列表添加到文件中的问题。所以我重写了,这是我的新代码:

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