使变量忘记之前的值

Make variables forget the previous values?

本文关键字:忘记之前 变量      更新时间:2023-10-16

我遇到了一个很烦人的问题。

首先,我写了一个只运行一次的程序,一切都很完美,直到我决定让它在用户输入的情况下可重新执行。

现在我有大麻烦了。当我重新执行程序时,由于变量没有重新初始化自己,它陷入了错误的switch或if语句。来描绘它:

// Libraries and other stuff
int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';
int main() {
do {
// Randomly assigning some numbers between 1-3 range into numA, numB and numC
...
// Converting the integers above into chars depending on the random numbers
switch (numA)
{
  case 1:
  numA = charA;
  break;
  case 2:
  numA = charB;
  break;
  case 3
  numA = charC;
  break;
}
switch (nu...
...
// A lot of IFs and SWITCHs that consistently changes the values above within themselves.
...
// Taking 1 input from user to re-execute the program
} while (input == 1)
return 0;
}

我知道我一开始没有正确初始化变量,把一切都搞砸了,但是当我开始创建它时,我不打算让它重新执行,现在我正在寻找最佳的逃避方式。我能不能让变量忘记它们之前携带的值?或者我真的需要从头开始重新初始化所有东西吗?

将变量的声明移到循环内的作用域中,以便每次循环时重新初始化它们。

int main() {
do {
//new scope
{
int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';
// Randomly assigning some numbers between 1-3 range into numA, numB and numC
...
// Converting the integers above into chars depending on the random numbers
switch (numA)
{
  case 1:
  numA = charA;
  break;
  case 2:
  numA = charB;
  break;
  case 3
  numA = charC;
  break;
}
switch (nu...
...
// A lot of IFs and SWITCHs that consistently changes the values above within themselves.
...
// Taking 1 input from user to re-execute the program
}//end of scope
} while (input == 1)

然而,你应该明白,使用未初始化的变量是未定义的行为,应该始终避免。

你的字符变量初始化(char charA = 'charA')是完全无效的。您不能在一个字符变量中存储6个字符串(5个字符和空终止符)。你应该使用char*或者这是一个简单的排版错误,它应该是char charA = 'A'

您将所有字符初始化为'c'。当你将所有字符初始化为'charA', 'charB' &'charC',但在初始化字符时,它只需要一个字符,如char ch1= '6', ch2='n' ;因为所有的初始化式都有一个共同的第一个字母,那就是'c'。这就是为什么所有初始化为'c'。
还有,当()的()时,你忘了在后面加分号。此外,您正在使用numA作为开关控制变量。,在switch语句中,您正在更改numA中的值。这不是错误的做法,而是不好的做法。很抱歉很多编辑,因为我在stackexchange应用程序上,我需要多次看到问题。