0
Does not work in double ???
public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } } in this code when I change int to double everywhere this code doesnt work and display error of lossy conversation between int and double ... plz suggest a correction or tell me how should I add no.s using the double and array
4 Respostas
+ 3
As per my knowledge, you cannot compare a interger type to double type .what i'm trying to tell is
for(double x=0; x<myArr.length; x++) {
sum += myArr[x];
}
if you are declaring x as double type then you cannot compare it to myArr.length which is an integer type .so my opinion is to keep the x variable as int type (or) you can use this type of for loop condition,(if it works).
for(double x=0; int( x) <myArr.length; x++) {
sum += myArr[x];
}
Hope this information helps!!!
+ 3
Hope it helped bud!!
+ 2
This works fine.
public class Program {
public static void main(String[] args) {
double [ ] myArr = {6.25, 42.1234, 3.6, 7.097};
double sum=0; // Needs to be double as well!!!
for(int x=0; x<myArr.length; x++) {
sum += myArr[x];
}
System.out.println(sum);
}
}
Make sure that you are also setting the variable sum to double as well.
+ 2
chaotic dawg and G Hemanth thank you guys for clearing my doubt ... in the for loop also I was putting x as double ... now I got the mistake ... that's it keeps on giving the int and double error