[英]Take input from a file and check The number is prime or not
在c ++中,我尝试从文件中获取输入,并检查数字是否为质数。 但是主要的问题是,如果其中一个数字不是素数,则下一个数字表示不是素数。
我在文件中的输入是1 2 3 4 5 6
对于前三位数字,当打印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())
如有任何疑问,欢迎您:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.