在手动求解此程序时,我正在获得不同的输出
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
您的书正确。您的手动解决方案是错误的,因为您没有考虑到循环内部进行的内存分配。
在第三次迭代之后,在您的char
阵列内,您拥有BAJJAB
,因为最后3个字母替换了第一个3。现在,在您的第4个迭代中,代码所做的是第三个字母,J,并替换了第四个字母。然后用第二个字母替换第五个字母,依此类推。但看!现在,1-3个字母不是双关语,但已经从以前的迭代变为BAJ。这就是为什么印刷的单词最终成为对称的单词
相关文章:
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 显示错误输出的简单数组排序程序
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 如何从Windows应用程序输出到标准?
- 我写了一个C++程序来模拟Enigma机器.我没有得到输出
- 如何使用C++读取另一个程序中的源代码输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 为什么这个程序的输出不如预期
- 在由Sublime文本3编译后在cmd上显示Java程序输出
- C++ 每次运行程序时我都会"nan"输出的问题
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 而循环:简单的除法程序输出零,不明白为什么
- 如何在 html 页面中插入 cgi 应用程序的输出?
- C 中的输出程序无明显的原因是白色的
- C++:更改简单输出程序的字体
- C++ 简单的输入/输出程序 + 枚举器
- C++字母等效数字代码输出程序
- 编译输出程序集