定义变量和 exp3 中的循环存在问题

定义变量和 exp3 中的循环存在问题

继续解决我的问题问题

我有循环问题\int_do_while:nn

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! LaTeX error: "kernel/command-already-defined"
! 
! Control sequence \l_number_int already defined.
! 
! See the LaTeX3 documentation for further information.
! 
! For immediate help type H <return>.
!............................................... 

在下面的代码中。当我手动更改时\l_element_int,定义的问题\l_number_int不会出现。

\documentclass[12pt]{article}

\usepackage{xparse}
\ExplSyntaxOn
\int_new:N \l_initial_number_int



\cs_new_protected:Npn \count_number_of_elements:Nn #1#2
{
    \int_new:N \l_number_int
    \int_set:Nn \l_number_int {1}
    \int_set:Nn \l_initial_number_int {#2}
    \int_do_while:nn
    {\l_initial_number_int != 1}
    {
    \int_incr:N \l_number_int
    \int_if_even:nTF {\l_initial_number_int}
        {\int_set:Nn \l_initial_number_int {\l_initial_number_int/2} } 
        {\int_set:Nn \l_initial_number_int {3*\l_initial_number_int + 1} }
    }
    \int_set_eq:NN #1 \l_number_int 
} 


\NewDocumentCommand{\MaxNumber}{ m }
{
    \int_new:N \l_bound_element_int
    \int_set:Nn \l_bound_element_int {#1}

    \int_new:N \l_element_int
    \int_set:Nn \l_element_int {2}

    \int_do_while:nn {\l_element_int < \l_bound_element_int}
    {
        \count_number_of_elements:Nn \l_tmpa_int {\int_use:N \l_element_int}
        \int_incr:N \l_element_int
        \int_use:N \l_element_int -- \int_use:N \l_tmpa_int\\

    }

}

\ExplSyntaxOff

\begin{document}

\MaxNumber{13}

\end{document}

答案1

永远不要在函数内声明变量。声明(\..._new:N)始终是全局的,显然每个名称只能声明一次。这样你就永远不会调用函数两次。

\documentclass[12pt]{article}

\usepackage{xparse}
\ExplSyntaxOn

\int_new:N \l_initial_number_int
\int_new:N \l_number_int
\int_new:N \l_bound_element_int
\int_new:N \l_element_int

\cs_new_protected:Npn \count_number_of_elements:Nn #1#2
{
    \int_set:Nn \l_number_int {1}
    \int_set:Nn \l_initial_number_int {#2}
    \int_do_while:nn
    {\l_initial_number_int != 1}
    {
    \int_incr:N \l_number_int
    \int_if_even:nTF {\l_initial_number_int}
        {\int_set:Nn \l_initial_number_int {\l_initial_number_int/2} } 
        {\int_set:Nn \l_initial_number_int {3*\l_initial_number_int + 1} }
    }
    \int_set_eq:NN #1 \l_number_int 
} 

\NewDocumentCommand{\MaxNumber}{ m }
{
    \int_set:Nn \l_bound_element_int {#1}

    \int_set:Nn \l_element_int {2}

    \int_do_while:nn {\l_element_int < \l_bound_element_int}
    {
        \count_number_of_elements:Nn \l_tmpa_int {\int_use:N \l_element_int}
        \int_incr:N \l_element_int
        \int_use:N \l_element_int -- \int_use:N \l_tmpa_int\\

    }

}

\ExplSyntaxOff

\begin{document}

\MaxNumber{13}

\end{document}

相关内容