Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

Javascript handling fractions in variables

I'm new to programming and was trying to write a simple program to find the slope of a line, and I was wondering how I could handle variables with fractions in them. Currently, if I assign any of the variables as a fraction I will get an error.

var oneX = prompt ("what is the X of the first coordinate?");
var oneY = prompt ("what is the Y of the first coordinate?");
var twoX = prompt ("what is the X of the second coordinate?");
var twoY = prompt ("what is the Y of the second coordinate?");

console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);

var yRes = twoY-oneY;
var xRes = twoX-oneX;

console.log(yRes);
console.log(xRes);

var slope = yRes/xRes

console.log(slope);

If you have any advice for making this program neater too, I'd be happy for it. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dont use eval! Unless you know what eval is, why you should and shouldnt use it.

If you simply want to allow fractions then you should allow for parsing it. For instance you could simple write your code as such:

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
    var res = +input;
    if(isNaN(res)) {
        // try parsing as fraction
        var strval = String(input);
        var ix = strval.indexOf('/');
        if(ix !== -1) {
            try {
                res = strval.substring(0, ix) / strval.substring(ix+1);
            } catch(e) {
            }
        }
    }
    return isFinite(res) ? res : NaN;
}

var oneX = parseUserInput(prompt ("what is the X of the first coordinate?"));
var oneY = parseUserInput(prompt ("what is the Y of the first coordinate?"));
var twoX = parseUserInput(prompt ("what is the X of the second coordinate?"));
var twoY = parseUserInput(prompt ("what is the Y of the second coordinate?"));

Or a very pretty way of writing it using @Jonasw's suggestion.

/*
* Tries to parse a users input, returns {@param input} as a number or
* attempts to parse the input as a fraction.
* @return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
  return +input.split("/").reduce((a,b)=> a/(+b||1));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...