Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...