I have programmed a simple math function using Visual Studio 2012. My function equals the value 3.833333 when evaluated at q = 1, and zero whenever q does not = 1. When I test the function using a "cout" line such as shown in the first part of the main() below, the function returns the correct value of 3.833333, and for any other value it will return the correct value of 0. However, when I use the function in a for loop such as shown below, the function always returns 0, even when i=1. I do not understand why this is so because the function clearly works when I input a number into it directly. Any insight as to why this happens would be greatly appreciated.
First, you should always use code tags so it's easier for others to read your code and help you. Secondly, the problem is probably due to the way computers store values for decimal numbers. It doesn't store the exact value so it's likely that your loop never actually stores 1 in i (it will get close though). You can use cout to check this to make sure I'm right. One way to fix this would be to include the math.h header file and use it's absolute value function like this:
fabs() returns the absolute value of its input so what that does is check to see if the difference between q and 1 is less than 0.0001. Basically, if q is close to one, even if it isn't exactly one, return 3.833... Tell me if this helped.