线性功能

时间:2018-11-06 19:13:49

标签: javascript jquery

我需要编写一个分段函数,该函数的取值范围可以从95到65,并将其转换为gpa值。诀窍是95 = 4.0、94 = 3.9、93 = 3.8、92 = 3.7,并且每个百分点继续下降0.1,直到达到65 = 1.0。我很烦恼如何在不手动输入大量else-if的情况下进行编码。

$("#theButton").click(function() {
    var perc = $("#perc").val();
    var hardperc = (1+((perc-65)/10));
    perc = parseFloat(perc);

2 个答案:

答案 0 :(得分:3)

如果您想要简单的线性归一化,那么下面的函数应该可以解决问题。您不必使用重复的逻辑或条件,而只需使用一些数学即可。

//Reusable Linear Normalization function
const linearNormalize = (fromMin, fromMax, toMin, toMax) => value => {
  //Normalize the input value
  var pct = (value - fromMin) / (fromMax - fromMin);
  var normalized = pct * (toMax - toMin) + toMin;

  //Cap output to min/max
  if (normalized > toMax) return toMax;
  if (normalized < toMin) return toMin;
  return normalized;
}

//Wrapper function with your specific inputs
const gradeToGpa = linearNormalize(65, 95, 1.0, 4.0);

console.log(gradeToGpa(78));

Scott Sauyetcurried functions建议:

const linearNormalize = (fromMin, fromMax, toMin, toMax) => value => {
  var pct = (value - fromMin) / (fromMax - fromMin);
  var normalized = pct * (toMax - toMin) + toMin;

  if (normalized > toMax) return toMax;
  if (normalized < toMin) return toMin;
  return normalized;
}

const gradeToGpa = linearNormalize(65, 95, 1.0, 4.0);

console.log(gradeToGpa(78));

答案 1 :(得分:1)

这应该有所帮助。您需要考虑不正确的值,例如大于95和小于65,但这应该可以帮助您入门。

function gpa(input){
  var thescore = (1 + ((input - 65) / 10)).toFixed(2);
    return thescore;
}

alert(gpa(94));

输出: 3.90

提琴:http://jsfiddle.net/d7x8qb40/