c++ - 如何在 while 循环中保存 int 值?

标签 c++

我的问题是,如何在 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;
        }

    }


}

最佳答案

在您的代码中,您当前根据赌博结果显示 CashWCashL

不幸的是,您只打印出结果,而没有将其存储到 xCash 中。因此,在下一次迭代中,您将使用相同的 xCash 值重新开始!

您可以通过在显示结果的行下方添加 xCash = CashW;xCash = CashL; 轻松解决此问题。

关于c++ - 如何在 while 循环中保存 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40272542/

相关文章:

c++ - 将 vector 的内容添加到 Capnproto map 对象中

c++ - 递增迭代器以指向另一个迭代器的下一个元素

c++ - reinterpret_cast 从类指针到 long

c++ - 用OpenGL画圆

c++ - CppUnit 可以用于嵌入式系统吗?

c++ - 在基于范围内自动传递的参数

c++ - 在非 pod 结构上使用 operator new + Initializer list

c++ - 如何在用户定义的tensorflow op中使用随机数?

c++ - 为什么 enable_shared_from_this 无法直接访问嵌入式 weak_ptr?

python - 指向引用的指针使用 ctypes