作业帮 > 综合 > 作业

制作简易计算器(具有能对两个数进行加、减、乘、除运算的简易计算器)

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/22 16:36:25
制作简易计算器(具有能对两个数进行加、减、乘、除运算的简易计算器)
分析:4个按钮调用的函数的代码相似,怎样优化代码?

使用javascript实现代码
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript">
function $$(id){
    return document.getElementById(id);
}
 
function calc(operator){
    var result ="";
    var first = $$('first').value;
    var second = $$('second').value;
    result += first;
    if(operator =='+'){
        result += '+';
        result += second;
        result += '=';
        result += parseInt(first) + parseInt(second);
        //$$('result').innerText = result; 下面这句写成这个也可
        $$('result').value = result;
    }else if(operator =="-"){
        result += '-';
        result += second;
        result += '=';
        result += parseInt(first) - parseInt(second);
        //$$('result').innerText = result;
        $$('result').value = result;
    }else if(operator =="*"){
        result += '*';
        result += second;
        result += '=';
        result += parseInt(first) * parseInt(second);
        //$$('result').innerText = result;
        $$('result').value = result;
    }else if(operator =="/"){
        result += '/';
        result += second;
        result += '=';
        result += parseInt(first) / parseInt(second);
        //$$('result').innerText = result; 
        $$('result').value = result;
    }
}
</script>
</head>
<body>
    <table>
        <tr>
            <td>
                第一个数
            </td>
            <td>
                <input type ="text" id ="first" />
            </td>
        <tr>
            <td>
                第一个数
            </td>
            <td>
                <input type ="text" id ="second" />
            </td>
        <tr>
            <td>
                运算符:
            </td>
            <td>
                <input type ="button" value ="+" onclick="calc('+')" />
                <input type ="button" value ="-" onclick="calc('-')" />
                <input type ="button" value ="*" onclick="calc('*')" />
                <input type ="button" value ="/" onclick="calc('/')" />
            </td>
        <tr>
            <td>
                结果是:
            </td>
            <td>
                <input type ="text" id ="result" />
            </td>
        </tr>
    </table>
</body>
</html>
请采纳……