C ++:cout语句使我的程序变得混乱?

时间:2013-08-30 16:14:26

标签: c++ error-handling syntax-error cout

#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:语法错误:缺少&#39 ;;&#39;之前&#39;&lt;&lt;&#;; C4430:缺少类型说明符-int假设,C2086&#39; int cout&#39;:几乎所有cout语句的重新定义,我不能找出原因。感谢任何和所有的帮助,请尽可能地愚蠢的事情,这是我的第一个C ++程序。

1 个答案:

答案 0 :(得分:3)

假设您已准确发布了您正在尝试编译的代码,请填写

等语句
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);