是否可以将具有变量的方程式的字符串转换为方程式? [英] Is it possible to convert A string that is an equation with a variable into a equation?

查看:77
本文介绍了是否可以将具有变量的方程式的字符串转换为方程式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将从prompt返回的字符串转换为方程式,但是parseFloat仅作为第一个数字和方程式中的符号返回,并在变量处停止.该变量将始终为= x.该程序旨在将代数表达式(例如15*x(5^4-56)*17/x=15)转换为表达式,并计算x的值.如果有人可以向我展示如何做到这一点,那将大有帮助.我当前正在使用多个提示,让用户将方程式放在x之前,然后将方程式放在x之后,然后在两者之间插入一个变量,并计算其值.

I need to convert a string returned from prompt into an equation, however the parseFloat returns as only the first number, and symbols in an equation, and stops at the variable. The variable will always = x. The program is designed to convert an algebraic expression say 15*x(5^4-56)*17/x=15 into an expression, and calculate the value of x. If someone could show me how to do this, it would help dramatically. I am currently using multiple prompts, having the user put in the equation before x, then the equation after x, then it inserts a variable in between the two, and calculates it's value.

我没有预定义的变量,它必须在x > 1000x != //an integer的等式中工作.

I have no variables predefined, and it must work in equations where x > 1000, or x != //an integer.

提前谢谢!

推荐答案

似乎是一个复杂的问题...

Seems to be a complex problem...

这是一个简单轻松的问题解决方案.希望您可以使用其中的一些组件.

This is a solution for a simple relaxed version of your problem. Hope you can use some components of this.

约束:

  1. x的答案应为0到1000之间的整数
  2. 表达式的左侧应为正确的javascript语法

var input = prompt("enter the equation");  //eg: x*x+x+1=241
var parts = input.split('=');

//solving equation starts
var x = 0;
var temp = eval(parts[0]);
while (temp != parts[1] && x<1000){
   x++;
   temp = eval(parts[0]);
}
var ans = (x<1000)?"answer is "+x:"this program cannot solve this";
//solving equation finishes
  
alert(ans);

您可以使用计算机科学中用于求解方程的一些数值方法来替换求解方程"部分(更多详细信息

You can replace the "solving equation" part with some numerical methods used in computer science to solve equations (more details here) . You will have to parse the left side of equation and map them to proper javascript expressions (as a string to execute with eval()) if you want to allow users to use your syntax.

这篇关于是否可以将具有变量的方程式的字符串转换为方程式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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