如何计算百分比

How to calculate percentage

下面的代码从文本文件中获取失败的索引并将其打印到网页上,下面的循环执行相同的操作,但用于传递。我想计算百分比,我尝试了下面的代码,但它 returns 0.0%.

我是新手程序员,请帮忙。

    int i = 0;
    while ((i = (secondLine.indexOf(failures, i) + 1)) > 0) {
        System.out.println(i);
        feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + resultString.length() + " tests.<br>";
    }

    int j = 0;
    while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
        System.out.println(j);
        feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";  
    }

    totalScore = j * 100 / resultString.length();
    System.out.println(totalScore);
    feedbackString += "Your submission scored " + totalScore + "%.<br>";

您想将除法设为浮点除法:

totalScore = (double)j * 100 / resultString.length();

这是假设 totalScore 是双数。

否则,j * 100 / resultString.length() 将使用 int 除法,因此如果 resultString.length() > 100,结果将为 0。

正如汤姆提到的,while 循环的条件:

while ((j = (secondLine.indexOf(passed, j) + 1)) > 0)

确保它只会结束一次 j <= 0。因此,难怪 (double)j * 100 / resultString.length() 是 0。

如果你想计算传球次数,你需要第二个计数器:

int j = 0;
int passes = 0;
while ((j = (secondLine.indexOf(passed, j) + 1)) > 0) {
    passes++;
    System.out.println(j);
    feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + j + "</strong> - Well done.</li>";  
}

然后

totalScore = (double)passes * 100 / resultString.length();

问题是 j 不是失败次数,它是失败的索引。因为你 indexOf returns -1 万一它没有找到元素并且你用它来标记搜索结束,它总是-1。加 1,你总是得到 j == 0。

你可以这样做:

String secondLine = "pfpffpfffp";
char failures = 'f';
char passed = 'p';

ArrayList<Integer> failuresList = new ArrayList<Integer>();
ArrayList<Integer> passedList = new ArrayList<Integer>();
String feedbackString = "";

for (int i = 0; i < secondLine.length(); i++) {
  char o = secondLine.charAt(i);
  if (o == failures) {
    failuresList.add(i);
  } else {
    passedList.add(i);
  }
}

int countFailures = failuresList.size();
int countPassed = passedList.size();
int countTotal = countFailures + countPassed;

for (int i = 0; i < failuresList.size(); i++) {
    System.out.println(failuresList.get(i));
    feedbackString += "<strong style='color: red;'><li>Failed: </strong><strong>" + i + "</strong> - " + "out of " + countTotal + " tests.<br>";
}
for (int i = 0; i < passedList.size(); i++) {
    System.out.println(passedList.get(i));
    feedbackString += "<strong style='color: green;'><li>Passed: </strong><strong>" + i + "</strong> - Well done.</li>"; 
}

double totalScore = countPassed * 100.0 / countTotal;
System.out.println(totalScore);
feedbackString += "Your submission scored " + totalScore + "%.<br>";
System.out.println(feedbackString);