我正在尝试编写一个简单的程序来计算有多少学生通过了考试,有多少学生未通过考试。 我只是想掌握“增强的 For 循环”的窍门,但我在 TextPad 中收到以下错误:(它与普通的 For 循环思想一起工作正常)
error: possible loss of precision
if(marks[element]>40.0){
^
required: int
found: double
我的程序代码是:
public class Lab9Tut12{
public static void main (String[]args){
int passed = 0;
int failed = 0;
double [] marks = new double[20];
for(int i=0;i<20;i++){
marks[i] = Math.random()*100;
System.out.printf("%.2f", marks[i]);
System.out.println();
}
for(double element:marks){
if(marks[element]>40.0){
passed++;
}
else{
failed++;
}
}
System.out.println("Passed: " + passed + " failed: " + failed);
}
}
最佳答案
直接写
if(element>40.0){
这应该可以解决问题。
增强的 for 循环为您提供列表/数组的元素,而不是索引。
关于java - 增强型 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351427/