将随机整数添加到total中?



我正在编写一个类似21点的程序。我首先生成一对随机的卡片,并存储这些数字的总和。如果用户愿意,则必须生成另一张卡,并且需要更新新的总数。下面是到目前为止的程序:

/*
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 << "nTotal: " << total << "nn";
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 << "nplay moren";
if (card_choice == "n")
cout << "nDo you want to play again?n";

/*cin >> choice;
total += choice;
cout << total;*/
return 0;
}

编译时,赋值的左操作数需要:lvalue错误。我如何正确地添加数字和更新变量?谢谢你!

您需要为加法和赋值操作符添加括号,如下所示。(我也认为你的意思是+=而不是=+,但我没有在代码中改变它。)

#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 << "nTotal: " << total << "nn";
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 << "nplay moren";
if (card_choice == "n")
cout << "nDo you want to play again?n";

/*cin >> choice;
total += choice;
cout << total;*/
return 0;
}

最新更新