So I'm trying to write a program and I've stumbled into a ditch. Basically here is the program in a nutshell
1 2 3 4 5 6 7 8 9
int somefunction (int a)
{
Does something
returns true or false
}
main
test some value in the function
if (somefunction(3) == true) // 3 is just an arbitrary number
cout << "something" << endl;
Is that if statement correct? Can you check if something is true like that or is there a better way to do it? I heard something about ternary operators...
If you want a function to return a Boolean value then you declare the function to do what you intend. Your function currently returns an integer, which can be treated as a Boolean value, 0 is treated as false and !0 is treated as true. I suspect you wanted:
1 2 3 4 5 6
bool somefunction(constint a)
{
bool ret(false);
// code to do something and potentially change 'ret' to 'true'
return ret;
}
Your function is almost fine. The problem is that a == i-1 will never be true because i will never go above a. You probably meant a == i, which would happen if the loop completed without hitting the break line.
The only other thing I would really suggest is get rid of the if/else and just return the condition:
1 2 3
// blech:
if (a == i) return (true);
elsereturn (false);
1 2
// better
return (a == i);
Although I personally find it to be more clear if you just return as soon as you know you'll be returning. So something like this is what I'd do:
1 2 3 4 5 6 7 8 9
bool test_prime(int a)
{
for (int i = 0; i < a; i++)
{
if (a % i == 0)
returnfalse; // we know the number isn't prime, so just return false here
}
returntrue; // otherwise if we made it through the loop, we know it's prime.
}
#include <iostream>
usingnamespace std;
bool test_prime(int a)
{
int i;
for (i = 0; i < a; i++)
{
if (a % i == 0)
returnfalse;
}
if (a == i) return (true);
}
int main()
{
if (test_prime(5) == true)
return 0;
}
#include <iostream>
#include <vector>
usingnamespace std;
bool test_prime(int a)
{
int i;
for (i = 1; i < a; i++)
{
if (a % i == 0)
returnfalse;
}
return (true);
}
int main()
{
/* vector <int> v;
int x = 1, y, z;
for (int x; x < 10; x++)
{
if (test_prime(x) == false ) cout << "Not prime";
}*/
if (test_prime(5) == true)
cout << "Hello world!" << endl;
return 0;
}
That's really a good idea. Otherwise the result of the modulo operation isn't defined. The runtime system should terminate the process in case of the right operand beeing 0 (maybe not the C/C++ system which allows nearly everything - often resulting in much more bulshit results than eveything).
That just checks if a number is divisible by two, and if it is it is prime, but if something is divisible by 2 it is not prime and the number can't be divisible by anything other than 1 or itself to be prime.