从文件中获取输入并检查数字是否为素数

Take input from a file and check The number is prime or not

本文关键字:是否 数字 检查 文件 获取 输入      更新时间:2023-10-16

在c++中,我尝试从文件中获取输入并检查数字是否为素数。但主要问题是如果其中一个数不是素数那么下一个数也不是素数ex-

我在文件中的输入是1 2 3 4 5 6

前3位显示素数,当输出num4时显示非素数,之后所有输入都显示非素数。这里的问题是我的代码-

int main()
{
int x,i,b=0,j;

int  a[15];//size of array more than number of entries in data file
ifstream infile;
infile.open("prog1_input.txt");//open the text file
if (!infile)
{
    cout << "Unable to open file";
    exit(1); // terminate with error
}
i=0;
while (!infile.eof())
{
    //To make array for column
    infile>>x;

    a[i]=x;

    for(j=2;j<x;j++)
    {
        if(x%j==0)
        {
            b++;
        }
    }

    if(b==0)
    {
        cout<<a[i]<<"t"<<"Prime"<<endl;
    }
    else
       cout<<a[i]<<"t"<<"Not Prime"<<endl;

    // cout <<a[i]<<endl;
    i++;
}
// To print entry
infile.close();
// getch();

}

在你的代码中,b永远不会重置回0

你需要做的是

if(b==0)
{
    cout<<a[i]<<"t"<<"Prime"<<endl;
} else {
   cout<<a[i]<<"t"<<"Not Prime"<<endl;
   b = 0;
}

乍一看,你必须在循环开始时重新初始化b

 if (!inline.eof())

如果你有任何问题,欢迎提问:)