从文件中获取输入并检查数字是否为素数
Take input from a file and check The number is prime or not
在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())
如果你有任何问题,欢迎提问:)
相关文章:
- 检查输入是否不是整数或数字
- 用于检查数字是否有数字或可被该数字的值整除的程序
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 如何使用递归检查数字是否有重复数字?
- 查找数字是否为 2 的幂的时间复杂度
- 将 C 函数转换为 C++ 以检查数字是否有效
- C ++:检查它是否是类中的数字
- 检查数字是否为素数的算法
- 如何检查用户的输入是否有效以及我正在寻找的数字?
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 如何确定integer_sequence在编译时是否包含给定的数字?
- 有没有办法检查用户输入是否是数字?
- 如何知道文本文件中的输入是否是 C++ 中的有效数字
- C++:这两种将数字写入矩阵的方式之间是否存在显着的速度差异?
- 如何检查cin是否与数组中的一组数字匹配
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 在C/C++中检查数字是否为整数(不带scanf/gets/etc)
- 检查字符串是否是数字,然后将该数字转换为 int?