Question

I am working on an assignment for my software development lecture and have been asked to code a for loop where the user is asked for two numbers, which will be the upper and lower bounds for a table to be displayed.

This is coded in BlueJ, if that helps(?)

This is the loop i have so far,i have asked for the two numbers outwith this loop and set all but the i variable as floats, the i as a double;

for (i = lowNum; i <= highNum; i++) {
         //find square of number
            squareNum = i * i;

         //find cube of number
            cubeNum = i * i * i;

         //find square root of number
            rootNum = Math.sqrt(i);

         //display under appropriate headings
 }

when i try and run it, a compiler error comes up saying possible loss of precision, required: float; found: double; i have tried to change the variable type to float but then a similar error (float and double being reversed) highlighting the i in the Math.sqrt(i); line of code.

Does anyone know how to fix this?

Was it helpful?

Solution

Math.sqrt() returns a double. Cast it to a float as follows: (float)Math.sqrt()

OTHER TIPS

Wouldn't it be better to just use a double in your own code as well? Then you a) don't have to bothered with type casting and b) have less chance of actually falling victim to the loss of precision that the compiler is so graciously trying to warn you about.

Doing the cast is more like telling the compiler to shut up in stead of accepting it's help, IMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top