将字符串转换为整数并计算 [英] convert string to integer and calculate

查看:29
本文介绍了将字符串转换为整数并计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个计算器,其工作方式如下:
用户将他的计算放在一个文本框中,例如:2+4+5;然后整个字符串将转换为整数并计算数字并显示结果:11;.我的代码如下:

I am making a calculator which will work as follows:
the user will put his calculation in a textbox eg: 2+4+5; then the whole string will be converted to integer and calculate the numbers and display the result:11;. My code is as follows:

脚本:

function solve() {  
    problem = parseInt(document.getElementById('prob'));   
    ans = document.getElementById('ansspace');  
    ans.innerHTML = problem  
}  

HTML:

<input type="text" id="prob">  
<br>  <input type="button" id="add" value="Add" onclick="solve()">  <br>  
<p id='ansspace'></p>

推荐答案

制作计算器真的没有简单的方法,但是为了让您的代码正常工作,您可以使用 eval:

There's really no easy way to make an calculator but for your code to work you can use eval:

function solve() {  
  var problem = document.getElementById('prob').value;   
  var ans = document.getElementById('ansspace');   
  ans.innerHTML = eval(problem);  
}  

这篇关于将字符串转换为整数并计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆