【问题标题】:How to calculate average percentage for a student in Java? [duplicate]如何计算Java学生的平均百分比? [复制]
【发布时间】:2021-07-27 12:07:19
【问题描述】:

我制作了一个小型 Java 程序,用于计算学生考试的百分比。我昨天刚开始用 Java 编程,所以遇到了一个 bug。代码如下:

public class Userinput {
public static void main(String[] args) {
    System.out.println("Hi dear Student. This is a percentage calculator.");
    Scanner sc = new Scanner(System.in);
    System.out.println("How many Subjects do you have?");
    int totalSubjects = sc.nextInt();
    System.out.println("Out of how many marks did you have your exams/tests?");
    int outOf = sc.nextInt();

    int actualOutof = outOf;
    int markSubjects1 = 0;
    int markSubjects2 = 0;
    int markSubjects3 = 0;
    int markSubjects4 = 0;
    int markSubjects5 = 0;
    int markSubjects6 = 0;
    int markSubjects7 = 0;
    int markSubjects8 = 0;
    int markSubjects9 = 0;
    int markSubjects10 = 0;
    int i = 0;
    int totalSubjectsActual = totalSubjects + 1;

    for (i=1; i<totalSubjectsActual; i++) {
        System.out.println("How many marks did you score in the next subject?");

        if (i == 1) {
            markSubjects1 = sc.nextInt();
        } else if (i == 2) {
            markSubjects2 = sc.nextInt();
        } else if (i == 3) {
            markSubjects3 = sc.nextInt();
        } else if (i == 4) {
            markSubjects4 = sc.nextInt();
        } else if (i == 5) {
            markSubjects5 = sc.nextInt();
        } else if (i == 6) {
            markSubjects6 = sc.nextInt();
        } else if (i == 7) {
            markSubjects7 = sc.nextInt();
        } else if (i == 8) {
            markSubjects8 = sc.nextInt();
        } else if (i == 9) {
            markSubjects9 = sc.nextInt();
        } else if (i == 10) {
            markSubjects10 = sc.nextInt();
        }
    }
    int outOfMarks = actualOutof*totalSubjectsActual;
    int startAverage = markSubjects1 + markSubjects2 + markSubjects3 + markSubjects4 + markSubjects5 + markSubjects6 + markSubjects7 + markSubjects8;
    int decimalMarks = startAverage/outOfMarks;
    int average = decimalMarks*100;

    System.out.println("Average Percentage for all Subjects: " + average + "%");
}};

所有代码都运行良好,除了最后一部分。当我尝试从结果中计算百分比时,它显示为 0 或 100。请帮助我解决这个问题...

【问题讨论】:

  • 你正在做整数除法,这就是你得到 0 或 1 的原因。使用 double 代替。

标签: java calculator percentage


【解决方案1】:

原因是,您使用 int 来计算百分比。

将最后四个变量从 int 更改为 double 或 float。

Int 无法显示小数。例如,如果您有 0.24 作为值,它将减少 0.24,并且只会显示 0

您可以使用其他一些东西来优化您的程序。尝试查看数组。

【讨论】:

  • 感谢您的回答。这太明显了。为什么我没有早点收到?非常感谢。
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
相关资源
最近更新 更多