+Xinok Subscriber² Posted August 7, 2004 Subscriber² Share Posted August 7, 2004 I'm still very much an amateur with C++, so please don't get too technical with me. I made a simple app which will list all the prime numbers starting with 1. For how simple it was, it turned to be a real pain to get it to work. This is the working code: #include <iostream> using namespace std; main() { int value = 1, mod = 2, loop = 0, temp = 0; while(loop < 1){ temp = value % mod; if(temp != 0) { mod++; } else { value++; mod = 2; } if(mod * mod > value) { cout << value << endl; value++; mod = 2; } } system("pause"); return 0; } Now if I simply replace 'else' with another if function: while(loop < 1){ temp = value % mod; if(temp != 0) { mod++; } if(temp = 0) { value++; mod = 2; } //changed the else here to an if if(mod * mod > value) { cout << value << endl; value++; mod = 2; } all it does is list 1, 2, 3, and doesn't do anything from there. I know I got it working, but I would like to know why using the if doesn't work correctly, for future reference. Link to comment Share on other sites More sharing options...
0 Oogle Posted August 8, 2004 Share Posted August 8, 2004 You're confusing the assignment operator, '=', with the equality operator, '=='. Link to comment Share on other sites More sharing options...
0 azcodemonkey Posted August 8, 2004 Share Posted August 8, 2004 Your code didn't work for me. It would skip 2. This code appeared to work for me. if( temp != 0 ) { ... } else if( temp == 0 && value != 2 ) { ... } At least, I think that is what you're trying to accomplish. Also, when testing equality, use a ==. A single = is assignment. Link to comment Share on other sites More sharing options...
Question
+Xinok Subscriber²
I'm still very much an amateur with C++, so please don't get too technical with me.
I made a simple app which will list all the prime numbers starting with 1. For how simple it was, it turned to be a real pain to get it to work.
This is the working code:
#include <iostream>
using namespace std;
main()
{
int value = 1, mod = 2, loop = 0, temp = 0;
while(loop < 1){
temp = value % mod;
if(temp != 0) { mod++; }
else { value++; mod = 2; }
if(mod * mod > value) { cout << value << endl; value++; mod = 2; }
}
system("pause");
return 0;
}
Now if I simply replace 'else' with another if function:
while(loop < 1){
temp = value % mod;
if(temp != 0) { mod++; }
if(temp = 0) { value++; mod = 2; } //changed the else here to an if
if(mod * mod > value) { cout << value << endl; value++; mod = 2; }
all it does is list 1, 2, 3, and doesn't do anything from there.
I know I got it working, but I would like to know why using the if doesn't work correctly, for future reference.
Link to comment
Share on other sites
2 answers to this question
Recommended Posts