Re: [Dev-C++] Whole numbers and perfect square
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Brian C. B. <bri...@ho...> - 2002-11-03 19:21:02
|
Hi Rafael,
> Is there a way to make the computer know when a number is a whole number
or
> a perfect square?
Yes, there is a method that I have used before (in calculating Pythagorean
theorem). Use the C library function sqrt to take the square root. Then to
see if the number is a perfect square (or a whole number), use the C library
function floor to round the number down to the nearest whole number. If the
two numbers are equal (the square root and the rounded square root), you
know that the number is a perfect square.
For example:
double Number;
double Result;
Result = sqrt(Number);
if (Result == floor(Result)){
cout << Number << " is a perfect square!" << endl;
}
Say, Number = 5, then
Result = 2.2
floor(Result) = 2
Not Perfect Square
Say, Number = 4, then
Result = 2
floor(Result) = 2
Is Prefect Square
I'm sure that there is a better and more efficient way, but that is a
method that has worked for me. Does that help?
Sincerely,
Brian C. Becker
Shall we accept good from God, and not trouble?
|