Posted: Mon Oct 03, 2005 8:28 pm Post subject: incorrect result -_-
code:
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
double thing;
thing = pow((27/1),(1/3));
printf ("%.2f", thing);
system ("PAUSE") ;
return 0;
}
This returns 1.00 where it should return 3.00. (It returns one no matter what input is in the power function so i assume the problem is there). Any suggestions? Using dev c++ compiler.
Sponsor Sponsor
md
Posted: Mon Oct 03, 2005 8:41 pm Post subject: (No subject)
well... 27/1 is 27 and 1/3 is one third. The problem is that you're using integers. When you devide one integer (say 1) by another (say 3) the compiler does the division, but instead of returning a floating point fraction it returns an integer value (in this case it returns 1, the value it returns is documented somewhere...). In pascal this does the same as:
Pascal:
function foo_pascal(x:integer; y:integer):integer;
begin
foo := x div y;
end;
To get the fractional value in C or C++ you must first cast one of the values into a float or a double. There are by far many ways to do it, but the one that wtd would probably insist upon is a static_cast<float> or static_cast<double> (I think that's right... you can always use (double)... ).
c++:
double foo_cpp(int x, int y) { return x / static_cast<double>y;
}
As for power()... I'm fairly certain that there's nothing wrong with it, but see what happens when you use the casting.
Hikaru79
Posted: Mon Oct 03, 2005 8:43 pm Post subject: (No subject)
For example:
code:
#include <stdio.h>
#include <math.h>
int main(int argc, char argv[])
{
float thing;
thing = pow((27.00/1.00),(1.00/3.00));
printf ("%f",thing);
return 0;
}
This will return 3.00. I just converted all those ints to doubles manually.
Tubs
Posted: Mon Oct 03, 2005 8:45 pm Post subject: (No subject)
thanks... i am kinda creeped out that you go to UW though. im like 15 minutes away WLU
md
Posted: Mon Oct 03, 2005 8:45 pm Post subject: (No subject)
Sure you can do it manually... but then what happens if you change the values for variables?
Hikaru79
Posted: Mon Oct 03, 2005 9:16 pm Post subject: (No subject)
Cornflake wrote:
Sure you can do it manually... but then what happens if you change the values for variables?
Oh, no, I agree that your way is the solution. I was just giving a solid example to demonstrate what you were saying. Obviously the function has to be able to evaluate other values besides the cube root of 27
wtd
Posted: Mon Oct 03, 2005 9:23 pm Post subject: (No subject)
Cornflake wrote:
There are by far many ways to do it, but the one that wtd would probably insist upon is a static_cast<float> or static_cast<double> (I think that's right... you can always use (double)... ).