为什么srand需要存储类?
这是我上一个问题的延续。我的二十一点项目已经完成了很多工作,但现在我遇到了另一个问题。我已经被困在这三天了。起初的问题是它每次都给出相同的数字。但后来我发现问题是我需要使用种子。但是出于某种原因,它说 srand 需要一个存储类?当我尝试给它一个时,它只会给我另一个错误。有人可以帮我解决这个问题吗?这是我的代码
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
using namespace std;
vector<int> handone(0);
vector<int> handtwo(0);
int handone_int = 0;
int handtwo_int = 0;
srand(time(NULL));
int starting_hand = rand() % 21 + 1;
int starting_hand_two = rand() % 21 + 1;
string n = "Yes";
int main() {
std::cout << "Welcome To BlackJack! ";
std::cout << "Your starting hand is " << starting_hand << "n";
while (handone_int < 21 && handtwo_int < 21) {
for (int i = 0; i < handone.size(); i++) {
handone_int = handone_int + handone[i];
} for (int i = 0; i < handtwo.size(); i++) {
handtwo_int = handtwo_int + handtwo[i];
}
cout << "Would you like to keep or hold? ";
cin >> n;
if (n == "keep" or n == "Keep") {
}
}
}
回答
您应该srand在某个函数体内调用 of 。
此外,变量应该足够小,不会导致堆栈溢出,并且除了main()这个程序之外没有用户定义的函数,所以我看不出有任何理由使用这么多全局变量。他们应该转向局部变量。
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
using namespace std;
int main() {
vector<int> handone(0);
vector<int> handtwo(0);
int handone_int = 0;
int handtwo_int = 0;
srand(time(NULL));
int starting_hand = rand() % 21 + 1;
int starting_hand_two = rand() % 21 + 1;
string n = "Yes";
std::cout << "Welcome To BlackJack! ";
std::cout << "Your starting hand is " << starting_hand << "n";
while (handone_int < 21 && handtwo_int < 21) {
for (int i = 0; i < handone.size(); i++) {
handone_int = handone_int + handone[i];
} for (int i = 0; i < handtwo.size(); i++) {
handtwo_int = handtwo_int + handtwo[i];
}
cout << "Would you like to keep or hold? ";
cin >> n;
if (n == "keep" or n == "Keep") {
}
}
}