# 怎么判断除数是否为0

Jeans5219 2015-10-18 03:35:12
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>计算器</title>
<script>

function check()
{
var n1 = document.getElementById('num1').value;
var n2 = document.getElementById('num2').value;

if(!isNumber(n1)||!isNumber(n2))
{
return false;
}

function isNumber(str)
{
var nums="1234567890.-";
for(var i=0;i<str.length;i++)
{
var ch=str.charAt(i);
if(nums.indexOf(ch)==-1)
return false;
}
return true;
}
</script>
<%
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
String operator = request.getParameter("operator");
if(num1==null)
num1="0";
if(num2==null)
num2="0";
if(operator==null)
operator="+";

double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
double reuslt = 0;
if(operator.equals("+"))
reuslt = n1+n2;
else if(operator.equals("-"))
reuslt = n1-n2;
else if(operator.equals("*"))
reuslt = n1*n2;
else if(operator.equals("^"))
reuslt = Math.sqrt(n1);
else if(operator.equals("%"))
reuslt = n1%n2;
else
reuslt = n1/n2;
%>
<body bgcolor=#97FFFF align="center">
<form action="cal.jsp" method="POST">
<h1>简易计算器</h1>

<option value="+" <%if(operator.equals("+")) out.println("selected");%>>+</option>
<option value="-" <%if(operator.equals("-")) out.println("selected");%>>-</option>
<option value="*" <%if(operator.equals("*")) out.println("selected");%>>*</option>
<option value="/" <%if(operator.equals("/")) out.println("selected");%>>/</option>
<option value="^"<%if(operator.equals("^")) out.println("selected");%>>^</option>
<option value="%"<%if(operator.equals("%")) out.println("selected");%>>%</option>
</select>

<input type="submit" value="计算" name="b1" onclick="return check()"/>
<input type="reset" value="重置" name="b2" /><br />

</form>
</body>
</html>
————————————————————————————————

...全文
1306 5 打赏 收藏 转发到动态 举报

5 条回复

hch126163 2015-10-19
• 打赏
• 举报

function check() { var n1 = document.getElementById('num1').value; var n2 = document.getElementById('num2').value; if(!isNumber(n1)||!isNumber(n2)) { alert("请输入数字！"); return false; } var op=document.getElementsByName('operator')[0].value; if((op=='/'||op=='%')&&parseInt(n2,10)==0){alert('.......');return false;} if(op=="^"&&parseInt(n1,10)<0){alert('.......');return false;}
Go 旅城通票 2015-10-19
• 打赏
• 举报

1#的改下这个就行 var op=document.getElementsByName('operator')[0].value;

• 打赏
• 举报

1楼的代码应该没有什么问题吧。 使用debugger调试一下就知道微小的不对在哪了。
Jeans5219 2015-10-18
• 打赏
• 举报

slwsss 2015-10-18
• 打赏
• 举报

function check() { var n1 = document.getElementById('num1').value; var n2 = document.getElementById('num2').value; if(!isNumber(n1)||!isNumber(n2)) { alert("请输入数字！"); return false; } var op=document.getElementsByName('operator').value; if((op=='/'||op=='%')&&n2=='0')return alert('.......'),false; if(op=="^"&&n1<0)return alert('.......'),false;

87,776

• 近7日
• 近30日
• 至今