Just a little bit of background on myself: I have some schooling experience in C, VB.Net, C#.net, Oracle, and MySQL. I have never taken a programming language into a great depth, and that is my current goal with C++. I have just started taking C++ seriously. I am working out of the book "C++ Without Fear". While I have been skimming over much of the early information, I try to work the examples and practice problems just to ensure that I am understanding the concepts. I am using Microsoft's Visual C++ 2010 Express IDE. Now, onto the problem:
#include <iostream>
#include <cmath>
usingnamespace std;
bool prime(double input);
int main(){
double input = 1;
while(input > 0){
bool primeNumber = 'true';
cout << "Enter a number to test if it is prime: " << endl;
cin >> input;
primeNumber = prime(input);
if(primeNumber){
cout << "The number is prime." << endl;
}
else{
cout << "The number is not prime." << endl;
}
}
cout << "You have chose to exit the program." << endl;
system("pause");
return 0;
}
bool prime(double input)
{
int intInput = input;
double sRoot = sqrt(input);
for(int i = 2; i <= sRoot; i++){
if(intInput % i == 0){
returnfalse;
}
}
}
The program above runs with no problems. I know that the if statement on the top of the program is correct. But before getting it into this state, I had to modify my original conditional. It used to read if(primeNumber == 'true'). When I would run the program with that condition in the if statement, it will evaluate every prime number as "The number is not prime." Did I somehow create a double negative?
Thanks for anyones time,
jermainStain
PS - Is there anything that I could do to make my future posts more understandable? I apologize for the code not displaying indented. I was hoping there was a way for me to upload an image instead. Thanks again :)
bool primeNumber = 'true';
You're trying to set primeNumber to a character literal, which would always be non-zero. true is a reserved word, so it should just be: bool primeNumber = true;
However, that's irrelevant since you overlay primeNumber with the return value from prime().
You have a problem in your prime() function. You return false if the number is evenly divisible, but you never return true when you fall through the for loop.
Should be:
1 2 3 4 5 6 7 8 9 10
bool prime(double input)
{ int intInput = input;
double sRoot = sqrt(input);
for(int i = 2; i <= sRoot; i++)
{ if(intInput % i == 0)
{ returnfalse;
}
}
returntrue; // not evenly divisible
}