# Problem with \ifthenelse inside some loops

Why this code produce some value not in the diagonal? Nine in total all below the diagonal.

\documentclass{article}
\usepackage{tikz}
\usepackage{ifthen}
\begin{document}

\begin{tikzpicture}
\clip[](.75,.75)rectangle(7.75,7.75);
\foreach \x in {1,...,7}
{
\foreach \y in {1,...,7}
{
%\pgfmathsetmacro{\rapporto}{\x/\y}
\pgfmathtruncatemacro{\rapporto}{\x/\y}
\ifthenelse
{1=\rapporto}
{\node[scale=1,red]at(\x,\y){$\x/\y$};}
{}
}
}
\end{tikzpicture}
\end{document}

• Please can you add or edit a compilable minimal working example? – Sebastiano Jan 15 '18 at 20:38
• Now it should be ok! – yngabl Jan 15 '18 at 20:42
• @yngabl no your example produces the error ! LaTeX Error: The font size command \normalsize is not defined: there is probably something wrong with the class file. – David Carlisle Jan 15 '18 at 20:49

It is because the \pgftruncatemacro will truncate your result, then some combinations of \x and \y will give 1. Use this:

\documentclass{article}
\usepackage{tikz}
\usepackage{ifthen}

\begin{document}

\begin{tikzpicture}
\clip[](.75,.75)rectangle(7.75,7.75);
\foreach \x in {1,...,7}
{
\foreach \y in {1,...,7}
{
\ifnum\x=\y
\node[scale=1,red]at(\x,\y){$\x/\y$};
\else
\relax
\fi
}
}
\end{tikzpicture}
\end{document}


To see why this is the case, output the entire (7 x 7) matrix of values \rapporto evaluates to:

\foreach \x in {1,...,7} {%
\foreach \y in {1,...,7} {%
\pgfmathtruncatemacro{\rapporto}{\x / \y}%
\rapporto~%
}%
\par
}


You'll see that the diagonal evaluates to 1, but also other elements (since truncation of values slightly larger than 1 will result in 1). If you want to focus on the diagonal, rather consider the condition \x = \y. Moreover, there is no need for ifthen:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\clip (.75, .75) rectangle (7.75, 7.75);
\foreach \x in {1,...,7} {%
\foreach \y in {1,...,7} {%
\ifx\x\y% \x == \y
\node [red] at (\x, \y){$\x / \y$};
\else% \x != y
\node [black] at (\x, \y){$\x / \y$};
\fi
}
}
\end{tikzpicture}

\end{document}

• What is the point of doing two loops and then just keeping the diagonal elements? – user121799 Jan 15 '18 at 20:48
• @marmot: True. I think the FALSE clause of the condition will speak to that, but it's been left empty. – Werner Jan 15 '18 at 20:50
• I agree. I agree. – user121799 Jan 15 '18 at 20:51