我在弄清楚如何在 cout 函数中隐藏特定变量(如果可能的话)时遇到了问题。基本上我需要做一个数字猜谜游戏,这很容易,除非我们的老师希望我们像随机数学方程式那样来做。老实说,这仍然相当容易,除了我们必须这样做的方式是程序必须随机创建问题,然后随机选择要显示的 3 个数字之一,用户必须猜测另外两个缺失的数字。例如,如果程序选择 20 + 32 = 52,它可能会显示 __ + 32 = __。
我已经做到了那么远,但是我不知道如何制作它所以它会像那样显示,但仍然允许我像这样放线
cout << num1 //Hidden << " + " << num2 << " = " << num3 //Hidden
但是就像我说的那样,我什至不知道这是否可行,否则我可能不得不重写整个程序。这是我目前所拥有的:
int main()
{
int num1, num2, num3, random1, guess1, guess2;
string play = "";
cout << "Would you like to run the number guessing program? (enter yes or no): ";
getline(cin, play);
for (int i = 0; i < play.length(); i++)
{
play[i] = tolower(play[i]);
}
//Random seed
srand(time(0));
while (play == "yes")
{
//Generate random numbers and num3
num1 = 1 + rand() % 50 + 1;
num2 = 1 + rand() % 50 + 1;
num3 = num1 + num2;
int pickRandom[3] = { num1, num2, num3 };
//Display random elements
random1 = pickRandom[rand() % 3];
if (random1 == num1){
cout << "\nYour randomly generated number problem: " << num1 << " + " << "__" << " = " << "__" << endl;
}
if (random1 == num2){
cout << "\nYour randomly generated number problem: " << "__" << " + " << num2 << " = " << "__" << endl;
}
if (random1 == num3){
cout << "\nYour randomly generated number problem: " << "__" << " + " << "__" << " = " << num3 << endl;
}
//Get Guesses
cout << "\nBased off of this information please make an educated guess as to what the two missing numbers are.";
cout << "\n\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
while ((guess1 > 100) || (guess1 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
}
cout << "\n\nGuess for number 2 (between 1 and 100): ";
cin >> guess2;
while ((guess2 > 100) || (guess2 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 2 (between 1 and 100: ";
cin >> guess2;
}
if (guess1 == )
}
return 0;
}
最佳答案
我认为您不能在cout
中隐藏变量。但是您可以使用变量而不是硬编码“__”。
例如,你可以简单地这样写:
if(guessed_var1_correctly)
var1 = num1
else
var1 = "__"
if(guessed_var2_correctly)
var2 = num2
else
var2 = "__"
if(guessed_var3_correctly)
var3 = num3
else
var3 = "__"
cout << "\nYour randomly generated number problem: " << var1 << " + " << var2 << " = " << var3" << endl;
其中 var1、var2、var3 是输出变量。如果玩家猜对了,它会显示实际值 num1、num2 或 num3。如果没有,它只会显示“__”。
关于c++ - 有没有办法在 cout (C++) 中隐藏变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552832/