Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
56 views
in Technique[技术] by (71.8m points)

c++ - Add random integer to total?

I am working on a blackjack-like program. I initially generate a random pair of cards and store the total of the numbers. If the user wishes to, another card must be generated, and the new total needs to be updated. Here is the program so far:

/*
Cortez Phenix
The 25th of January, 2021
CS10B, Mr. Harden
Assignment 2.1

This program uses...
*/

#include <cstdlib>
#include <iostream>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
    srand(static_cast<unsigned>(time(nullptr)));

    string card_choice;
    string repeat_choice;
    int num_1 = rand()%10+1;
    int num_2 = rand()%10+1;
    int total = num_1 + num_2;

    cout << "First Cards: " << num_1 << ", " << num_2;
    cout << "
Total: " << total << "

";

    do{
    cout << "Do you want another card? (y/n) ";
    cin >> card_choice;
    }
    while (card_choice == "y" && total += rand()%10+1);

    if (card_choice == "y")
        cout << "
play more
";

    if (card_choice == "n")
        cout << "
Do you want to play again?
";


    /*cin >> choice;
    total += choice;
    cout << total;*/

    return 0;
}

When compiled, there is an error: lvalue required as left operand of assignment. How do I properly add the numbers and update the variable? Thank you!

question from:https://stackoverflow.com/questions/65894160/add-random-integer-to-total

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you need to add brackets for the addition and assignment operator as following. (also I think you mean += instead of =+ but I didn't change it in the code.)

#include <iostream>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
    srand(static_cast<unsigned>(time(nullptr)));

    string card_choice;
    string repeat_choice;
    int num_1 = rand()%10+1;
    int num_2 = rand()%10+1;
    int total = num_1 + num_2;

    cout << "First Cards: " << num_1 << ", " << num_2;
    cout << "
Total: " << total << "

";

    do{
    cout << "Do you want another card? (y/n) ";
    cin >> card_choice;
    }
    while (card_choice == "y" && (total =+ rand()%10+1));

    if (card_choice == "y")
        cout << "
play more
";

    if (card_choice == "n")
        cout << "
Do you want to play again?
";


    /*cin >> choice;
    total += choice;
    cout << total;*/

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...