#include <iostream>
#include <string>
#include <random>
#include <Windows.h>
using namespace std;
int playerHP = 20;
int enemyHP = 20;
int playerAtk =(rand()%4 + 5); //Find a random number between 5 and 8
int playerDef = (rand()%4 + 5);
int playerAgi = (rand()%4 + 5);
int enemyAtk = (rand()%4 + 4); //Find a random number between 5 and 7
int enemyDef = (rand()%4 + 4);
int enemyAgi = (rand()%4 + 4);
cout<<"---------------"<< endl; // what in the sam hill is going on
cout<<"FIGHTER STATS"<< endl;
cout<<"----------------"<<endl;
cout<<"Player Stats:"<<endl;
cout<<"HP "<<playerHP<<endl;
cout<<"ATK "<<playerAtk<<endl;
cout<<"DEF "<<playerDef<<endl;
cout<<"AGI "<<playerAgi<<endl;
cout<<"ENEMY STATS:"<<endl;
cout<< "HP "<<enemyHP<<endl;
cout<<"ATK "<<enemyAtk<<endl;
cout<<"DEF "<<enemyDef<<endl;
cout<<"AGI "<<enemyAgi<<endl;
我似乎无法弄清楚为什么cout语句在程序中创建了如此多的错误。显然这不是我的整个程序,但我想让事情简短有趣。我收到错误C2143:语法错误:缺少';'在'<
最佳答案
假设您已经准确地发布了您要编译的代码,则如下语句
cout<<"---------------"<< endl;
需要在函数内部。
早先的行不会导致错误,因为它可以有效地声明任何函数之外的具有全局范围的变量。不过,这不是一个好习惯,如果仅单个函数需要使用变量,则当然不应该使它们成为全局变量。
尝试将所有代码移到
main
函数中。即int main()
{
int playerHP = 20;
int enemyHP = 20;
int playerAtk =(rand()%4 + 5);
// rest of your code goes here
}
编译并运行代码后,您会发现随机数始终被初始化为相同的值。您需要先调用
srand
,然后选择一次运行之间不同的值,然后再调用rand
。如果您不介意每秒仅更改一次,那么当前时间是一个容易选择的种子int main()
{
int playerHP = 20;
int enemyHP = 20;
srand(time(NULL));
int playerAtk =(rand()%4 + 5);
关于c++ - C++ : cout statements making my program go haywire?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18537360/