3

I'd like to set up a LaTeX template for grading, which would contain several categories that are graded individually using A-F by the user of the template. Out of these, the final grade has to be computed as the arithmetic mean of them.

I define three functions:

  1. Convert A-F to a numeric value (\gradetovalue).
  2. Compute a mean (\calculatemean).
  3. Convert the value back to grade (\valuetograde).

However, I have no idea how to do the second step. I've looked at some simple usage of fpeval from the xfp package, but I only ended up with a bunch of compilation errors when the argument includes other things than constants.

Simplified example here:

\documentclass{article}
\usepackage{xstring}

% Definitions %
\newcommand{\gradetovalue}[1]{%
\IfStrEq{#1}{A}{1.0}
{\IfStrEq{#1}{B}{1.5}
{\IfStrEq{#1}{C}{2.0}
{\IfStrEq{#1}{D}{3.0}
{\IfStrEq{#1}{E}{4.0}
{\IfStrEq{#1}{F}{5.0}
{Error}
}}}}}}

\newcommand{\calculatemean}{%
    % Return (\gradetovalue{\categoryA} + \gradetovalue{\categoryB} + \gradetovalue{\categoryC}) / 3
}

\newcommand{\valuetograde}[1]{%
\newdimen \x
\x = #1pt
\ifdim \x < 1.24pt A \else
\ifdim \x < 1.74pt B \else
\ifdim \x < 2.44pt C \else
\ifdim \x < 3.44pt D \else
\ifdim \x < 4.44pt E \else F
\fi\fi\fi\fi\fi
}

\newcommand{\finalgrade}{\valuetograde{\calculatemean}}


% User should provide these %
\newcommand{\categoryA}{B}
\newcommand{\categoryB}{A}
\newcommand{\categoryC}{D}


\begin{document}

Grades in categories are: \categoryA, \categoryB, \categoryC. The final grade is \finalgrade.

\end{document}
1

1 Answer 1

6

You can use \dimexpr for this calculation, because you are using \x as dimen.

\def\gradeA{1.0}
\def\gradeB{1.5}
\def\gradeC{2.0}
\def\gradeD{3.0}
\def\gradeE{4.0}
\def\gradeF{5.0}

\def\gradetovalue#1{\csname grade#1\endcsname}

\newdimen\x
\def\finalgrade{%
   \x=\dimexpr (\gradetovalue\categoryA pt + \gradetovalue\categoryB pt + \gradetovalue\categoryC pt) / 3 \relax
   \ifdim \x < 1.24pt A \else
   \ifdim \x < 1.74pt B \else
   \ifdim \x < 2.44pt C \else
   \ifdim \x < 3.44pt D \else
   \ifdim \x < 4.44pt E \else F
   \fi\fi\fi\fi\fi
}

\def\categoryA{B}
\def\categoryB{A}
\def\categoryC{D}

Grades in categories are: \categoryA, \categoryB, \categoryC. The final grade is \finalgrade.

\bye

And use \newdimen outside your macro.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .