Monday, May 24, 2010

Why does error "Illegal use of floating point value in function main()" in C++ code?

I'm doing a decimal to binary, octal and hexadecimal converter using C++. Actually, the code is still unfinished and I haven't started with the octal and hexadecimal part. Here's the code:





#include %26lt;iostream.h%26gt;


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





int main ()


{


double input, i, j, k, bin, oct, hex, counter, power;


char ans = 'y';





do


{


bin = 0;


oct = 0;


hex = 0;


counter = 1;


i = 1;


j = 1;


power = 1;


k = 0;





system ("cls");





cout %26lt;%26lt; "Enter an integer number [1-50]: ";


cin %26gt;%26gt; input;





while (counter %26lt; input)


{





while (i %26gt; 0)


{


j = i % 2;


k = k + pow(j,power);


power = power + 1;


}





cout %26lt;%26lt; bin;


}





} while (ans == 'y' || ans == 'Y');





return 0;


}

Why does error "Illegal use of floating point value in function main()" in C++ code?
First, almost all of your variables should probably be int, not doubles (floats). Unless you're dealing with possible fractional values (currency, for example) or potentially very large numbers (astronomical distances), ints are preferable.





That being said, the j = i % 2 could be the line causing the error. Using a mod operator (%) on a floating point value is a dubious operation, if it's even legal.





Hope that helps.





Edit: Just checked with Visual C++ Help system: "The operands of the remainder operator (%) must be integral. " This was the Standard C++ definition.





Edit in response to Additional Details: How do you get out of the innermost while loop? Look carefully at it.
Reply:No, actually, don't listen to Jeff G. Istream's operator%26gt;%26gt; is overloaded to many cases.





And by the way, i is never modified in the while loop. Do you see any i= or i%26lt;something%26gt;= in your while loop?





EDIT: Your do...while loop is also infinite because ans is never modified. You may want a cin%26gt;%26gt;ans just before the while line (not the one in the middle, the one at the end).





EDIT: Uhhhhhhhhhhhh...


I think your whole conversion process may be flawed. If I may, let me try to replace that internal while:





//Oh,. and set power to the highest power you want printed out.





while(i%26gt;0%26amp;%26amp;power%26gt;=0){ //FAILSAFE-no infinite loops because power is always decreased.


while(i%26gt;pow(j, power)){ //Increases the digit every time.


bin+=pow(10, power); //Inc this digit


i-=pow(j,power); //Take this out of the sum


}


}





//We SHOULD get here with power==0, if power


//is -1, a logic error occured and the while was terminated on


//the second term.





cout%26lt;%26lt;bin%26lt;%26lt;(power==-1?"LOGIC ERROR\n":"\n");


No comments:

Post a Comment