Tuesday, July 28, 2009

What is wrong with my c++ code?? Im getting an illegal use of floating point in main error?

Is there an easier way of doing this? What about an infinite series? Anyway here is the code that I am using with the Borland Compilier.





double sum = 0;


for (double i = m; i %26lt;= n; i++)


sum = sum+(1/(n^2));


Total = sum;


std::cout %26lt;%26lt; Total %26lt;%26lt; std::endl;


return 0;


}





"file1.cpp": E2060 Illegal use of floating point in function main() at line 21

What is wrong with my c++ code?? Im getting an illegal use of floating point in main error?
This error can only have happened if you have declared n as a float or double.





I guess it's an integer so declare n as an int and it will compile (I have verified this with Borland).





Alternatively you can use math.h and call pow for this one.





Change the line





sum = sum+(1/(n^2));





to





sum = sum+(1/(pow(n,2)));





and





#include %26lt;math.h%26gt; for pow.





That way you do not have to change the declaration of n.





x^y is not guaranteed to compile unless they are both ints.


pow takes 2 doubles and returns a double so no restriction.
Reply:dont use double in for loop,


ie double i gives this error


so better use while loop in this case.


if you wabt to use for loop type cast m and n to int.
Reply:plz refer to the last line...the curly bracket...


where is the open curly bracket?
Reply:Is "m" declared? You're setting m to i, but it's not declared in that code snippet.


No comments:

Post a Comment