这段代码的问题是,我发现了一个作家的普及为0%(我的意思是百分之零如果借图书的数量是14和借来的所选作者的书籍总数为3 - 它应该是21.42% ).为什么会这样?
除最后一个外,所有结果都是正确的:
作者0%受欢迎(对于上面给出的数据)
<%
String requestedoprations = request.getParameter("popularity");
if("check".equalsIgnoreCase(requestedoprations)){
int num=LimsHandler.getInstance().popularitycheck(
request.getParameter("selectedauthor"));
if(num!=0){
Limsdetails[] list = LimsHandler.getInstance().libsdetails();
String totbks=list[0].getTot_books();
String totbrwdbk=list[0].getTot_borrowed_bks();
int totbksint=Integer.parseInt(totbks);
int totbrwdbksint=Integer.parseInt(totbrwdbk);
float per=(num/totbrwdbksint)*100;
%>
<font color="brown">
<b>Total No of Books Available in Library is : <%=totbksint %><br></br>
Out of which <%=totbrwdbksint %> are borrowed.<br></br>
<b>No of readers reading Author
<%=request.getParameter("selectedauthor") %>'s book. :
<%=num %></b><br></br>
<b> Author <%=request.getParameter("selectedauthor") %> is <%=per %> %
popular!</b><br></br>
</font>
<%}else{ %>
<h4 align="center">
<font color="red">
<img border="0" src="images/close.PNG" ><br></br>
Oops! some error occurred!
</font>
</h4>
<%
}
out.flush();
%>
<%} %>
Run Code Online (Sandbox Code Playgroud)
这不是一个JSP问题 - 它是Java处理整数运算的方式.相关的路线是:
int num = LimsHandler.getInstance().popularitycheck(...);
int totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / totbrwdbksint) * 100;
Run Code Online (Sandbox Code Playgroud)
您正在执行"int/int"除法然后乘以100.这将使用整数运算执行除法- 因此结果将为0.将0乘以100仍然得到0.
解决它的最简单方法是使其中一个值为a float
或double
.例如:
int num = LimsHandler.getInstance().popularitycheck(...);
float totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / totbrwdbksint) * 100;
Run Code Online (Sandbox Code Playgroud)
或者,您可以在表达式中强制转换:
int num = LimsHandler.getInstance().popularitycheck(...);
int totbrwdbksint = Integer.parseInt(totbrwdbk);
float per = (num / (float) totbrwdbksint) * 100;
Run Code Online (Sandbox Code Playgroud)
此时,将使用浮点运算执行除法,您将得到您期望的答案.