rand数和变量(C ++)

时间:2011-10-18 20:27:03

标签: c++ variables if-statement

制作文字游戏,基本上我创建兰特数,但当数字等于if变量时if变量不运行,为什么?我研究了它但找不到答案。我知道这是一个新手问题。

#include <cstdlib>
#include <iostream>

using namespace std;
int main()
{
    string name;
    string FDF;
    int plus_damage;
    int plus_mana;
    int health;
    int mana;
    int wep;
    int mon;
    cout << " Hello and welcome to Sams and Toms game." << endl;
    system("pause");
    cout << " What is your name ?" << endl;
    cin >> name;
    cout << " Well hello, " << name << endl;
    system("cls");
    system("pause");
    cout << " What weapon would you like to start with, " << name << endl;
    system("pause");
    system ("cls");
    cout << " A list of weapons is " << endl;
    cout << " An axe, +2 extra damage. A sword, +2 extra damage. And a staff, +4 mana." << endl;
    system("pause");
    cout << " Enter one for the axe, two for the sword and 3 for the staff, " << name << endl;
    cin >> wep;
    system("cls");
    if (wep==1) {
        cout << " You chose the axe, +4 weapon damage! " << endl;
        plus_damage = (plus_damage + 4);
        cout << " So, lets start!" << endl;
        srand((unsigned)time(0));
        int mon = rand()%2;
    }
    if (mon==1) {
        cout << "A chicken appears" << endl;
    }
    if (mon==2) {
        cout << " A bitch appears" << endl;
    }
}

4 个答案:

答案 0 :(得分:3)

rand()%2可以为您提供的两个值为01,而不是12

P.S。我没有尝试编译您的代码,但是大括号似乎在int mon = ...if (mon==1)...

附近搞乱了

答案 1 :(得分:1)

mon超出了if条件的范围。你需要在if(wep == 1)的范围之外声明mon。现在你写了一个新的lokal变量mon。

 int mon;
 ...
 if(wep==1){
 ...
     mon = rand()%2;
 }

使用点击可让您的代码更易于阅读。

答案 2 :(得分:1)

您的mon函数的最外面的块中有一个未初始化的变量main()

您的mon函数的最后两个块中有一个初始化变量main()。得到一个随机数。然后它超出了范围......所以随机初始化就消失了。

因此,请从

中删除int
    int mon = rand()%2;

答案 3 :(得分:0)

rand()%2会给你0或1 此外,在您的情况下,编译器将向您提供有关已声明mon的错误 请将if子句中的int mon =更改为mon =

...
int mon;
...
if (wep==1) {
    ...
    mon = rand() % 2 + 1;
}
...