Computer Science Canada incorrect result -_- |
Author: | Tubs [ Mon Oct 03, 2005 8:28 pm ] | ||
Post subject: | incorrect result -_- | ||
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. |
Author: | md [ Mon Oct 03, 2005 8:41 pm ] | ||||
Post 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:
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)... ).
As for power()... I'm fairly certain that there's nothing wrong with it, but see what happens when you use the casting. |
Author: | Hikaru79 [ Mon Oct 03, 2005 8:43 pm ] | ||
Post subject: | |||
For example:
This will return 3.00. I just converted all those ints to doubles manually. |
Author: | Tubs [ Mon Oct 03, 2005 8:45 pm ] |
Post subject: | |
thanks... i am kinda creeped out that you go to UW though. im like 15 minutes away WLU |
Author: | md [ Mon Oct 03, 2005 8:45 pm ] |
Post subject: | |
Sure you can do it manually... but then what happens if you change the values for variables? |
Author: | Hikaru79 [ Mon Oct 03, 2005 9:16 pm ] |
Post 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 |
Author: | wtd [ Mon Oct 03, 2005 9:23 pm ] |
Post 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)... ).
[syntax="cpp"]static_cast<double>(int_value)[/code] Would be correct. However, the original poster is clearly using C, as evidenced by the use of stdiol, so instead we use: [syntax="c"](double)int_value[/code] |
Author: | md [ Mon Oct 03, 2005 10:25 pm ] |
Post subject: | |
thanks wtd, wasn't quite sure on the syntax there |