[英]I am getting different output while solving this program manually
作为一项任务,我必须推测该程序的输出:
#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
你的书是正确的。 您的手动解决方案是错误的,因为您没有考虑在for循环内执行的内存分配。
在第3次迭代后,在char
数组中有BAJJAB
因为后3个字母已替换了前3个字母。现在在第4次迭代中,代码执行的操作是将第3个字母J替换为第4个字母。 然后用第二个字母替换第五个字母,依此类推。 但看! 现在,这1-3个字母不是PUN,而是已经从以前的迭代更改为BAJ。 这就是为什么印刷字最终成为对称字的原因
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.