Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

possible lossy conversion from double to int error in exercise 2.2. how to debug?

+4 votes
for this problem i tried the tricky way of using math.pow get the the sum of squares but ran into a double to int error. changing the variable to a double instead of an int produced the wrong answer because it gave me a .0 at the end of the sum.

for( int i=1; i<=10;i++){
    int square = Math.pow(i,2);
    System.out.print( square + " ");}
asked Sep 7, 2017 in CSC 211 (F17) by Emilio Moscosa (100 points)

2 Answers

0 votes

The Math.pow method returns your result as a double itself. You attempting to return the double as an int is what the lossy conversion is. You can use some casting  to be able to still use Math.pow and have it return an int.

answered Sep 7, 2017 by Caleb Westerman (100 points)
0 votes

We haven't learned about Math.pow yet...  so it's simpler to just use 

i * i

which gives you back an int, which is what you want!

answered Sep 8, 2017 by Forrest Stonedahl (100 points)