gpt4 book ai didi

java - 获取两个变量的百分比

转载 作者:行者123 更新时间:2023-12-02 11:26:55 26 4
gpt4 key购买 nike

我尝试过对我的变量使用强制转换,以及我在这里读到的有关获取百分比的其他一些技巧,但代码在这里不起作用。当然,还有更多内容。从选角到展示,我已经尝试了所有方法。

(EDITED AGAIN 2nd time)

这是完整的代码。你是对的,它正在工作,但在这方面,它不是!即使等级变量是 floatint,仍然不起作用。更改了成绩变量,使其不显示小数!。输出(如下)显示等级,但不显示百分比。感谢您的反馈。

输出:

Please enter a grade from 0 - 100! Enter -1 to end the program! 99 
Please enter a grade from 0 - 100! Enter -1 to end the program! -1
The total number of grades is 2
Number of A's = 1 which is %0.0
Number of B's = 0 which is %0.0
Number of C's = 0 which is %0.0
Number of D's = 0 which is %0.0
Number of F's = 0 which is %0.0

代码: 公共(public)类主要{

public static void main(String[] main) {

Scanner input = new Scanner(System.in) ;

int totalGrades = 1 ;

int gradeA = 0 ;
float gradeAPercentage = (gradeA * 100f) / totalGrades ;

int gradeB = 0 ;
float gradeBPercentage = gradeB / totalGrades ;

int gradeC = 0 ;
float gradeCPercentage = gradeC / totalGrades ;

int gradeD = 0 ;
float gradeDPercentage = gradeD / totalGrades ;

int gradeF = 0 ;
float gradeFPercentage = gradeF / totalGrades ;

int a = 0 ;

do{
System.out.println("Please enter a grade from 0 - 100! Enter -1 to end the program!") ;
int grade = input.nextInt() ;

if( (grade == -1) && (totalGrades == 0) ) {
System.out.println("You entered no grades!") ;
totalGrades--;
break ;
}
else if(grade == -1){
a++ ;
}
else if(grade <= 59){
gradeF++ ;
totalGrades++ ;
}
else if( (grade >= 60) && (grade <= 69) ){
gradeD++ ;
totalGrades++ ;
}
else if( (grade >= 70) && (grade <= 79) ){
gradeC++ ;
totalGrades++ ;
}
else if( (grade >= 80) && (grade <= 89) ){
gradeB++ ;
totalGrades++ ;
}
else if( (grade <= 100) && (grade >= 90) ){
gradeA++ ;
totalGrades++ ;
}
else{
System.out.println("Your input is Invalid") ;
continue ;
}
}while(a < 1 ) ;

System.out.println("The total number of grades is " + totalGrades) ;
System.out.println("Number of A's = " + gradeA + " which is %" + gradeAPercentage) ;
System.out.println("Number of B's = " + gradeB + " which is %" + gradeBPercentage) ;
System.out.println("Number of C's = " + gradeC + " which is %" + gradeCPercentage) ;
System.out.println("Number of D's = " + gradeD + " which is %" + gradeDPercentage) ;
System.out.println("Number of F's = " + gradeF + " which is %" + gradeFPercentage) ;
}
}

最佳答案

已完成隐式转换,无需额外转换为 float 。您提供的代码工作正常。如果您使用

打印结果
System.out.println(gradeAPercentage);

您将得到您想要计算的结果。

关于java - 获取两个变量的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49550162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com