我的问题是,如何在 while 循环中保存一个 int 值,我的代码都是关于赌博的,你从 1,000 开始,你想赚最多的现金,但是当我再次滚动时,我的现金恢复了回到我设置的原始值。
我的代码是这样的(注意我是新手所以不要笑它有多糟糕)
#include <cmath>
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
char again = 'Y';
int test;
int yes;
int CashW;
CashW = 1000;
int CashL;
CashL = 1000;
int yLose;
yLose = 500;
int xCash;
xCash = 1000;
int xRan;
srand(time(0));
xRan = rand() % 100 + 1;
cout << " Welcome to the Gambling Game!" << endl;
cout << " If the number is above 50 I win!" << endl;
cout << " If the number is below 50 you lose!" << endl;
while (again == 'y' || again == 'Y')
{
cout << " The Number I Choose Is: " << xRan << endl;
CashL = xCash - xCash - xCash;
CashW = xCash + xCash;
if (xRan < 50) {
cout << " You win, rats!" << endl;
cout << " The cash you started with was: " << xCash << endl;
cout << " The cash you have now is: " << CashW << endl;
cout << " Type 1 to play again, type 2 to close the game." << endl;
cin >> yes;
}
if (xRan > 50) {
cout << " I win, you lose!" << endl;
cout << " The cash you started with was: " << xCash << endl;
cout << " The cash you have now is: " << CashL << endl;
cout << " Type 1 to play again, type 2 to close the game." << endl;
cin >> yes;
}
if (yes == 1) {
cout << " Cool, a gambling man! Time to make some cash" << endl;
}
}
}
最佳答案
在您的代码中,您当前根据赌博结果显示 CashW
或 CashL
。
不幸的是,您只打印出结果,而没有将其存储到 xCash
中。因此,在下一次迭代中,您将使用相同的 xCash
值重新开始!
您可以通过在显示结果的行下方添加 xCash = CashW;
或 xCash = CashL;
轻松解决此问题。
关于c++ - 如何在 while 循环中保存 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40272542/