2013-05-16 142 views
4

我对C++非常陌生,而且我写下了这段代码。其目的是在此以去.. 1.问叫名字,那么欢迎的人 2.询问他们的选择 3.精选的武器随机数和损害熊猫C++程序过早结束

我有所有3这些步骤工作。然后我决定也许我可以通过在我的rand()函数括号中使用变量来改变我的随机数的范围。这没有按计划运作,所以我尝试恢复原状。预先感谢收到的任何帮助。我不知道如何通过互联网搜索,所以我来到这里..希望有人能够发现我的问题。我正在使用netbeans IDE。

我的问题: 它首先要求我的名字,然后我输入我的名字,它欢迎我。但是,它完成了代码。甚至在尝试其他代码之前。我的想法是,我显然错过了我应该改回的东西。

Welcome to panda hunter! Please enter your name: Darryl 
Welcome!, Darryl! 

RUN SUCCESSFUL (total time: 3s) 

但我已经看了很多次,并且找不到任何错误。此外,我的想法是,这条线有什么问题,因为这是它无法做到并得到进一步的地方:

cout << "Pick your weapon of choice! Then press enter to attack: "; 

。这里是整个文件的内容:

#include <iostream> 
#include <cstdlib> 
#include <stdio.h>  /* printf, scanf, puts, NULL */ 
#include <stdlib.h>  /* srand, rand */ 
#include <time.h> 

using namespace std; 

string getName(){ 
    string name; 
    cin >> name; 
    return name; 
} 
string weaponChoice(){ 
    string weapon; 
    cin >> weapon; 
    return weapon; 
} 
int rand(){ 
    int damagePanda = rand() % 20 + 1; 
    return damagePanda; 
} 
int main() { 

    srand(time(0)); 
    int pandaHealth = 100; 
    int userHealth = 100; 


    cout << ("Welcome to panda hunter! Please enter your name: "); 
    cout << "Welcome!, " << getName() << "!" << endl; 
    cout << "Pick your weapon of choice! Then press enter to attack: "; 
    cout << "You surprise the panda with your " << weaponChoice() << ", dealing " << rand() << " damage!"; 
    pandaHealth = pandaHealth - rand(); 
    cout << "Panda has " << pandaHealth << " health remaining"; 

    char f; 
    cin >> f; 
    return 0; 
} 
+4

'getName'函数看起来很奇怪。 –

+0

失踪的结局。我不在C++中,但在某些平台上可能是'cout << flush'。 –

+0

您需要刷新输出缓冲区。在'<< std :: endl'标记到发送到'std :: cout'的每一行的末尾。 –

回答

10
int rand(){ 
    int damagePanda = rand() % 20 + 1; 
    return damagePanda; 
} 

递归调用。你可能在这里吹你的堆栈。

编译器应该在这里提醒你!不知道为什么没有。

更改为

int myrand(){ 
    int damagePanda = rand() % 20 + 1; 
    return damagePanda; 
} 

而且改变

cout << "You surprise the panda with your " 
<< weaponChoice() << ", dealing " << rand() << " damage!"; 

cout << "You surprise the panda with your " 
<< weaponChoice() << ", dealing " << myrand() << " damage!"; 

这也可能需要改变

pandaHealth = pandaHealth - rand(); 

这最后的改变可能取决于你的应用程序逻辑 - 我没有试图去理解它。

+0

+1 Nice catch。虽然我不认为我以前见过“[可能的]无限递归调用”错误。 – Dukeling

+4

您还应该将myrand()结果存储在一个int中,而不是将其调用两次,以便为cout和实际损坏计算使用相同的值。 –

+0

现在完美运作!非常感谢你。是的,编译器应该说些什么,但显然它不想。我还添加了船长所说的''std :: endl'的位,非常感谢您收到的所有帮助。将此标记为答案! –