在手动求解此程序时,我正在获得不同的输出

I am getting different output while solving this program manually

本文关键字:输出 程序      更新时间:2023-10-16

作为分配,我必须推测此程序的输出:

#include <iostream>
#include <ctype.h>
#include <string.h>
void change (char* state, int &s)
{
    int b = s;
    for (int x = 0; s>=0; x++, s--)
    if ((x+s)%2)
        *(state+x) = toupper(*(state+b-x));
}
int main ( )
{
    char s[] = "Punjab";
    int b = strlen(s) - 1;
    change (s, b);
    std::cout<<s<<"#"<<b;
}

根据我的书,在编译和执行时,该程序应输出:

 bajjab#-1 

问题是我的猜测是执行代码,将是

 bajnup#-1 

而不是。

我在某个地方犯了一个错误,但是在哪里?

在纸上运行代码时,最好跟踪变量所需的值。

int b = strlen(s) - 1;给出5。

现在change()内,

b拥有s的值,即5。

现在关注这里:

for (int x = 0; s>=0; x++, s--)
  if ((x+s)%2)
    *(state+x) = toupper(*(state+b-x));

x == 0, s == 5,其中其总和甚至都不是,因此%2不会导致0,导致IF语句的主体执行并将state[5]写入state[0]

现在x增加了1,s减少了1,因为s >= 0评估为true。

等等...完成纸质运行后,您可能需要在程序的每个步骤(实际运行在计算机上运行),并将它们与您的每个步骤进行比较在纸上制作。

示例:

#include <iostream>
#include <ctype.h>
#include <string.h>
void change (char* state, int &s)
{
    int b = s;
    for (int x = 0; s>=0; x++, s--)
    {
        std::cout << "x = " << x << ", s = " << s << ", x + s = " << x + s << ", (x + s) % 2 = " << (x + s) % 2 << "n";
        if ((x+s)%2)
        {
            std::cout << "state[" << x << "] = state[" << b - x << "]n";
            *(state+x) = toupper(*(state+b-x));
        }
        std::cout << "state = "" << state << ""n";
    }
}
int main ( )
{
    char s[] = "Punjab";
    int b = strlen(s) - 1;
    change (s, b);
    std::cout<<s<<"#"<<b;
}

输出:

x = 0, s = 5, x + s = 5, (x + s) % 2 = 1
state[0] = state[5]
state = "Bunjab"
x = 1, s = 4, x + s = 5, (x + s) % 2 = 1
state[1] = state[4]
state = "BAnjab"
x = 2, s = 3, x + s = 5, (x + s) % 2 = 1
state[2] = state[3]
state = "BAJjab"
x = 3, s = 2, x + s = 5, (x + s) % 2 = 1
state[3] = state[2]
state = "BAJJab"
x = 4, s = 1, x + s = 5, (x + s) % 2 = 1
state[4] = state[1]
state = "BAJJAb"
x = 5, s = 0, x + s = 5, (x + s) % 2 = 1
state[5] = state[0]
state = "BAJJAB"
BAJJAB#-1

您的书正确。您的手动解决方案是错误的,因为您没有考虑到循环内部进行的内存分配。

在第三次迭代之后,在您的char阵列内,您拥有BAJJAB,因为最后3个字母替换了第一个3。现在,在您的第4个迭代中,代码所做的是第三个字母,J,并替换了第四个字母。然后用第二个字母替换第五个字母,依此类推。但看!现在,1-3个字母不是双关语,但已经从以前的迭代变为BAJ。这就是为什么印刷的单词最终成为对称的单词