在这张图片中:有 6 个交叉点。当交叉点数量发生变化时,我需要 6 个自动更改。你能帮助我吗?
我的代码:
\documentclass[tikz,border=5mm]{standalone}
\usepackage[utf8]{vietnam}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[smooth]
\draw[gray!30](-3,-3) grid (3,3);
\draw[->](-3,0)--(3,0) node[below]{$x$};
\draw[->](0,-3)--(0,3) node[right]{$y$};
\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{(\x)^3-3*(\x)})
node[right, red] {$y=x^3-3x$};
\draw[red,name path=tron] (0,0) circle(2);
\fill[violet,name intersections={of=hamso and tron,name=A,total=\t}]
\foreach \i in {1,...,\t} {(A-\i) circle (2pt) node[above]{\i}};
\path (current bounding box.south) node[below]{There are: \fbox{6} intersection points};
\end{tikzpicture}
\end{document}
答案1
我相信 Henri 想告诉你,你只能将其设为\t
全局(或将其从路径中偷运出去)。实现这一点的一种方法是将其添加\pgfextra{\xdef\myt{\t}}
到存储\t
在全局宏中的路径中\myt
。(可以找到偷运的高级可能性,例如这里,但我认为在这里你几乎必然需要全球化宏。)编辑:也处理 0 个交叉点的情况。
\documentclass[tikz,border=5mm]{standalone}
\usepackage[utf8]{vietnam}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}[smooth]
\draw[gray!30](-3,-3) grid (3,3);
\draw[->](-3,0)--(3,0) node[below]{$x$};
\draw[->](0,-3)--(0,3) node[right]{$y$};
\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{(\x)^3-3*(\x)})
node[right, red] {$y=x^3-3x$};
\draw[red,name path=tron] (0,0) circle(2);
\fill[violet,name intersections={of=hamso and tron,name=A,total=\t}]
\ifnum\t>0
foreach \i in {1,...,\t} {(A-\i) circle (2pt) node[above]{\i}}
\fi
\pgfextra{\xdef\myt{\t}};
\path (current bounding box.south) node[below]{There are: \fbox{\myt} intersection points};
\end{tikzpicture}
\end{document}
如果将三次曲线改为
\draw[blue,name path=hamso] plot[domain=-2.1:2.1] (\x,{7+(\x)^3-3*(\x)})
node[right, red] {$y=7+x^3-3x$};
你会得到