Hello,
I am now to C++ (I started yesterday), and I am trying to make a program that spits out prime numbers. My method is to divide an odd number by every number less than one half that number and see if the result is an integer or not. This requires me to check if a variable is an integer. Is this possible?
Here's the code. I have put "y!=an integer" in the places where I need to check if y is an integer.
#include <iostream>
using namespace std;
int main()
{
int n=1, x;
double y;
NewNumber:
y=0.5;
for (x=2; y!=an integer, x<(n/2); x++) y=n/x;
if (y!=an integer) {
n=n+2;
goto NewNumber;
}
else {
n=n+2;
cout << n << "\n";
goto NewNumber;
}
return 0;
}
'Integer' has not been declared as an 'int'. This means the compiler will not know what 'integer' is. If you want to check if the number is a whole number, than you should try and check if the number has an no remainder.
so use the remainder operator. (modulus): %
This will make sure that the number has no remainder an therefore cannot be a decimal.
When / is used on two integers the result will be an integer (fractional part discarded). If you want / to give you a double make sure that at least one of the operands to / is of type double. You can do that with a cast. y = static_cast<double>(n) / x;
One way to check if y is an integer is to see if y is equal to y rounded down to closest integer. y == std::floor(y)
You can use % but then you have to use it on n and x. If the remainder of the division between n and x is 0, n is divisible by x; (n % x) == 0