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?

+2 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 in CSC 211 (F17) by Emilio Moscosa (181 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 by Caleb Westerman (579 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 by Forrest Stonedahl (3,153 points)
...