Okay to start out I need some help with this small program. I started recently learning C++, and this is one of the examples in the book what I want to know about it is on line 33 where it has the word "double" inside (). I have tried to find it on the forms but to no avail, due in no small part to my lack of xp. I think that it's changing the type but I can't be sure.
thanks.
#include <iostream>
#include <math.h>
int prime(int n);
int main()
{
int i;
//set up infinate loop. break if user enters 0.
//otherwise, evaluate n from prime-ness.
while(1)
{
std::cout << "\nEnter a number (0 to exit) and press ENTER: ";
std::cin >> i;
if(i == 0)
{
break; // exit
}
if(prime(i)) //call prime
{
std::cout << std::endl << i << " is prime.";
}
else
{
std::cout << std::endl << i << " is not prime.";
}
}
}
int prime(int n)
{
int i;
for(i = 2; i <= sqrt((double)n); i++)
{
if(n % i == 0)
returnfalse;
}
returntrue;
}
I think that it's changing the type but I can't be sure.
You are correct. It is called "casting".
In your example, that is an old style cast, inherited from the C language.
As a C++ programmer you should favor using the new style casts of C++, for clarity:
34 35 36 37
for (i = 2; i <= sqrt(static_cast<double> (n)); i++)
{
// ...
}