[英]Prime number finding program using bool values
I am trying to write a program in C++ that, given a data file that includes random integers, identifies each integer as prime or not prime, and counts the integers. 我试图用C ++编写一个程序,给定一个包含随机整数的数据文件,将每个整数标识为素数或非素数,并对整数进行计数。 Here is what I have so far: 这是我到目前为止的内容:
#include <iostream>
using namespace std;
int main()
{
int number; //number to be tested
int count = 0; //count of integers in file
cin >> number;
while (cin)
{
bool prime = true;
if (number <= 0)
{
prime = false;
}
else
{
for (int i=2; i<number; i++)
if (number % i == 0)
{
prime = false;
break;
}
}
if (prime = true)
cout << number << " is a prime number." << endl;
if (prime = false)
cout << number << " is not a prime number." << endl;
cin >> number;
count++;
}
cout << "The file contains " << count << " integers" << endl;
return 0;
}
The program compiles, but finds all values in a data set as not prime. 该程序进行编译,但是发现数据集中的所有值都不是素数。 Here is what I got as output from a data file: 这是我从数据文件中得到的输出:
24 is a prime number. 24是质数。
13 is a prime number. 13是质数。
18 is a prime number. 18是质数。
-25 is a prime number. -25是质数。
42 is a prime number. 42是质数。
0 is a prime number. 0是质数。
2 is a prime number. 2是质数。
The file contains 7 integers 该文件包含7个整数
Any suggestions? 有什么建议么? Am I using the bool values correctly? 我是否正确使用布尔值? Thank you 谢谢
You are using the assignment operator =
instead of the equality comparison operator ==
when checking if prime
is true or false. 在检查prime
是true还是false时,您正在使用赋值运算符=
而不是相等比较运算符==
。 (You should also use braces for your for
loop.) (你也应该用括号为您for
循环。)
Heads up that you can check the factors until prime/2
(or sqrt(prime)
, see below) since nothing greater than half of a number can be a factor of it! 请注意,直到prime/2
(或sqrt(prime)
,请参见下文)之前,您都可以检查这些因数,因为不超过一半的数字可能是一个因数!
This line: 这行:
if (prime = true)
cout << number << " is a prime number." << endl;
is assigning "true" to variable "prime". 为变量“ prime”分配“ true”。 As a expression, an assignment operation returns the value being assigned, so the expression inside the if evaluates as true and hence, prints that the number is prime. 作为表达式,赋值操作返回要赋值的值,因此if内的表达式的值为真,因此输出该数字为质数。
You have to change = by == . 您必须通过==更改=。 An old trick to avoid these mistakes is to change the sentence as this: 避免这些错误的一个老技巧是将句子更改为:
if (true = prime)
cout << number << " is a prime number." << endl;
Then the compiler had warned you about the obvious error. 然后,编译器已警告您有关明显的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.